首页 > 解决方案 > mvn 测试失败,但如果按包运行则测试通过

问题描述

我有一个具有以下结构的项目

src
  |_ main
  |   |_ java
  |       |_ com.company.product
  |           |_ packageA
  |           |_ packageB
  |_ test
      |_ java
          |_ com.company.product
              |_ packageA
              |_ packageB

运行时mvn test,我在 packageA 中的测试通过,而在 packageB 中的测试失败。运行时mvn test -Dtest="com.company.product.packageB.**",packageB 中的测试通过。此外,运行 mvn test -Dtest="com.company.product.**"也会使 packageB 测试失败,而不是 packageA 测试。为什么mvn test没有通过所有应该通过的测试?

packageB 中的测试详情:

@Test
void createNew() {
    String user = "testUser";

    //This calls a third party API that is throwing a 
    //InvocationTargetException when running packages together
    Connection connect = new Connection(user);
    String resultText = connect.getResultText();

    assertNotNUll(connect);
    assert (resultText).equals("Process Complete");
}

运行第三方 API 调用所需的 jar 包含在 pom 中,如下所示。

    <dependency>
        <groupId>com.third.party.api</groupId>
        <artifactId>third-party-api</artifactId>
        <version>1.0.0</version>
    </dependency>

使用 Java 1.8.0_74 和 Maven 3.5.4。

编辑: Maven返回的错误:

createNew()  Time elapsed: 0.001 sec  <<< ERROR!
java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
        at com.company.product.packageB.MyTest.createNew(MyTest.java:11)
Caused by: java.lang.reflect.InvocationTargetException
        at com.company.product.packageB.MyTest.createNew(MyTest.java:11)
Caused by: java.lang.RuntimeException: Error when creating RpcClientStub. Cause : java.lang.NoClassDefFoundError: Could not i
nitialize class com.third.party.apitransport.session.ArRpcCallContext
        at com.company.product.packageB.MyTest.createNew(MyTest.java:11)

...

Results :

Tests in error:
  MyTest.createNew:11 » Runtime java.lang.reflect.InvocationTargetEx...
  MyTest.createAndUpdate:29 » Runtime java.lang.reflect.Invocation...
  MyTest.connect:51 » Runtime java.lang.reflect.InvocationTarget...

Tests run: 9, Failures: 0, Errors: 3, Skipped: 0

编辑:正如 Ivan 在评论中指出的那样,修复是添加清理。

private static String systemOsName;
@BeforeAll
public static void setOsName(){
    systemOsName = System.getProperty("os.name");
}
...
@AfterAll
public static void cleanup(){
    Constants.setFilePathSeparator("");
    System.setProperty("os.name",systemOsName);
}

标签: javamavenintellij-ideajunit

解决方案


如果有多个测试正在设置该System.setProperty("os.name", "windows")值,那么如果该值用于稍后在您的包 b 测试中确定一个值,则需要在最后进行清理并重置该值。


推荐阅读