mvn测试失败,但如果按包运行则测试通过

时间:2018-09-27 15:50:18

标签: java maven intellij-idea junit

我有一个结构如下的项目

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);
}

1 个答案:

答案 0 :(得分:1)

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

相关问题