2011-02-18 164 views
4

我對Java編程和JUnit測試還是比較新的。我使用了junit-4.5附帶的NetBeans 6.9.1(但我已將junit-4.8.2添加到我的庫中)。JUnit:運行同時測試

我有很多測試類,每個類都有一些@Test方法。

當我運行一個特定的Test類時,它每次運行一個@Test方法。我還創建了一個測試套件

@RunWith(Suite.class) 
@Suite.SuiteClasses(value = { 
    TestClassA.class, 
    TestClassB.class, 
    TestClassC.class}) 
public class NewTestSuite { 
} 

將通過我的每個測試類的運行,並在每個運行每個@Test方法。

我的問題是:我可以同時運行測試類嗎?或者,在每個測試類中可以同時運行@Test方法?

這樣做可以讓我運行所有測試的速度要快於一次一個地運行類和方法。

謝謝!

+0

單元測試運行多長時間? – khmarbaise 2011-02-18 13:46:57

+0

任何地方從不到一秒到30-60秒。應用程序與數據服務器通信,所以我想同時運行多個請求來加速測試。 – kmccoy 2011-02-18 13:57:37

回答

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

你可以試試這個簡單的例子: 我添加了一個斷言,因爲在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); 
     } 
    } 
}