简体   繁体   English

如何从头开始运行 JUnit 类或测试方法

[英]How to run JUnit classes or test methods from scratch

I have JUnit tests located in different test folders, when I'm running them one by one everything is green all tests are passed in particular folder, but when its done in scope (all at once), some tests are failing due to some data is changed during previous tests execution.我的 JUnit 测试位于不同的测试文件夹中,当我一一运行它们时,一切都是绿色的,所有测试都在特定文件夹中通过,但是当它在范围内完成时(全部一次),由于某些数据,某些测试失败在之前的测试执行期间发生了变化。 So it's a way to run JUnit tests from scratch, I've tried所以这是一种从头开始运行 JUnit 测试的方法,我试过了

mvn "-Dtest=TestClass1,TestClass2" test

but some tests are failed.但有些测试失败了。 When its done like:当它完成时:

mvn "-Dtest=TestClass1" test

all passed.都过去了。 Or when:或者当:

`mvn "-Dtest=TestClass2" test

all passed.都过去了。

As long as TestClass1 and TestClass2 share common state there might be no way to run them together eg it could be a static field somewhere in the JVM.只要TestClass1TestClass2共享公共状态,就可能无法将它们一起运行,例如它可能是 JVM 中某处的static字段。 You must refactor the tests so they are isolated and have no side effects eg use @Before and @After to clean up resources after the test.您必须重构测试,以便它们被隔离并且没有副作用,例如使用@Before@After在测试后清理资源。

You could play with Maven Surefire Plugin options to spawn a new JVM for each test but it would be very inefficient.您可以使用 Maven Surefire Plugin 选项为每个测试生成一个新的 JVM,但这会非常低效。

For this specific problem, you can create a TestSuite.对于这个特定问题,您可以创建一个 TestSuite。

Create Two Test Suite Classes Attach @RunWith(Suite.class) Annotation with the class.创建两个测试套件类 将 @RunWith(Suite.class) 注释与类附加在一起。

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)

@Suite.SuiteClasses({
   TestJunit1.class
})

public class JunitTestSuite1 {   
}  


@RunWith(Suite.class)

    @Suite.SuiteClasses({
       TestJunit2.class
    })

    public class JunitTestSuite2 {   
    }  


public class TestRunner {
   public static void main(String[] args) {
      Result result1 = JUnitCore.runClasses(JunitTestSuite1.class);
      Result result2 = JUnitCore.runClasses(JunitTestSuite2.class);

      for (Failure failure : result1.getFailures()) {
         System.out.println(failure.toString());
      }
      for (Failure failure : result2.getFailures()) {
         System.out.println(failure.toString());
      }


      System.out.println(result1.wasSuccessful());
      System.out.println(result2.wasSuccessful());
   }
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM