JUnit:运行同步测试

时间:2011-02-18 13:41:41

标签: java junit junit4 netbeans-6.9

我仍然是Java编程和JUnit测试的新手。我使用了junit-4.5附带的NetBeans 6.9.1(但我已将junit-4.8.2添加到我的库中)。

我有许多测试类,每个类中都有许多@Test方法。

当我运行一个特定的Test类时,它一次运行一个@Test方法。我还创建了一个带

的测试套件
@RunWith(Suite.class)
@Suite.SuiteClasses(value = {
    TestClassA.class,
    TestClassB.class,
    TestClassC.class})
public class NewTestSuite {
}

将遍历我的每个测试类,并在每次运行中运行每个@Test方法。

我的问题是:我可以同时运行测试类吗?或者,在每个测试类中,是否可以同时运行@Test方法?

这样做可以让我比一次一个地运行类和方法更快地完成所有测试。

谢谢!

2 个答案:

答案 0 :(得分:7)

使用 org.junit.experimental.ParallelComputer : 样品:

    public class NewTestSuite {

       public static void main(String[] s){

         Class[] cls={TestClassA.class,TestClassB.class,TestClassB.class };  

         //simultaneously all methods in all classes  
         Result result = JUnitCore.runClasses(new ParallelComputer(true, true), cls);
         System.out.print(result.wasSuccessful());

         //simultaneously among classes  
         //Result result = JUnitCore.runClasses(ParallelComputer.classes(), cls);  

         //simultaneously among methods in a class  
         //Result result = JUnitCore.runClasses(ParallelComputer.methods(), cls);  
      }
   } 

答案 1 :(得分:1)

你可以试试这个简单的例子: 我添加一个断言,因为在JUnitCore中,我们没有内置。

public class TestParallelExecution {
private Logger logger = LoggerFactory.getLogger(TestParallelExecution.class);

@Test
public void runAllTest(){
    //add test class
    Class[] testClasses={testClass1.class, testClass2.class, };

    //Parallel execute only classes
     Result resultClasses = JUnitCore.runClasses(ParallelComputer.classes(), testClasses);

    //Parallel execute only methods in classes
    Result result = JUnitCore.runClasses(ParallelComputer.methods(), testClasses);

    //Run Parallel all methods in all test classes which declare in testClasses[]
    //method accept new ParallelComputer(classes, methods)
    Result result = JUnitCore.runClasses(new ParallelComputer(true, true), testClasses);
    List<Failure> failures = result.getFailures();


    if(result1.wasSuccessful() != true){
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < failures.size(); i++){
            sb.append(System.lineSeparator());
            sb.append("<---------------New test method--------------->");
            sb.append(System.lineSeparator());
            sb.append(failures.get(i).toString());
            sb.append(System.lineSeparator());
        }
        File file = new File("C:\\..\\FailedTest.txt");
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
            writer.write(sb.toString());
            writer.close();
        } catch (IOException e) {
            logger.trace("I can't create file,because : ", e);
        }
        //logger.error(sb.toString());
        assertTrue(false);
    }else {
        assertTrue(true);
        }
    }
}