【问题标题】:Tests Run fine in Eclipse but failed in mvn command测试在 Eclipse 中运行良好,但在 mvn 命令中失败
【发布时间】:2017-10-27 06:51:05
【问题描述】:

测试非常非常简单的测试

@RunWith(MockitoJUnitRunner.class)
public class UnitTestMyCode {

  @InjectMocks
  private MyClass resource;

  @Mock
  private DependentBean bean;

  @Test
  public void test1() throws Exception {
    boolean ss = true;
    assertThat(ss).isTrue();
}

错误

org.mockito.exceptions.base.MockitoException: Field 'resource' annotated with @InjectMocks is null.
Please make sure the instance is created *before* MockitoAnnotations.initMocks();
Example of correct usage:
   class SomeTest {
      @InjectMocks private Foo foo = new Foo();

      @Before public void setUp() {
         MockitoAnnotations.initMock(this);

    at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl$1.withBefores(JUnit45AndHigherRunnerImpl.java:27)
    at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:276)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)

Surefire 插件配置

   <plugin>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.4.2</version>
        <executions>
          <execution>
            <id>default-test</id>
            <phase>test</phase>
            <goals>
              <goal>test</goal>
            </goals>
            <configuration>
              <excludes>
                <exclude>**/*IntegrationTest*.java</exclude>
              </excludes>
              <includes>
                <include>**/*UnitTest*.java</include>
              </includes>
              <skip>false</skip>
            </configuration>
          </execution>
        </executions>
        <configuration>
          <excludes>
            <exclude>**/*IntegrationTest*.java</exclude>
          </excludes>  
          <includes>
                <include>**/*UnitTest*.java</include>
          </includes>            
          <skip>false</skip>
        </configuration>
      </plugin>

我已按照JUnit tests pass in Eclipse but fail in Maven Surefire 的步骤进行操作 但没有运气。

这里有任何帮助。

【问题讨论】:

  • 您是否尝试过错误提示您执行的操作?
  • Maven 永远是对的。你能展示你的 mockito 依赖吗?
  • 您使用的是非常旧的 maven-surefire-plugin 版本。此外,您为什么要进行如此多的配置。遵循命名约定让生活更轻松......是的,整个 pom 文件是个好主意......
  • 即使使用 mockito verison 3.0.0,我也面临这个问题。任何帮助

标签: java maven maven-surefire-plugin


【解决方案1】:

更新 Mockito 解决了这个问题

<dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-all</artifactId>
        <version>1.10.19</version>
        <scope>test</scope>
</dependency>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-09
    • 2020-10-25
    • 1970-01-01
    • 2017-07-23
    • 2016-03-22
    • 2021-10-31
    相关资源
    最近更新 更多