2011-04-03 130 views

回答

35

Junit4提供使用ParallelComputer平行特徵:

public class ParallelComputerTest { 

    @Test 
    public void test() {  
     Class[] cls={ParallelTest1.class,ParallelTest2.class }; 

     //Parallel among classes 
     JUnitCore.runClasses(ParallelComputer.classes(), cls); 

     //Parallel among methods in a class 
     JUnitCore.runClasses(ParallelComputer.methods(), cls); 

     //Parallel all methods in all classes 
     JUnitCore.runClasses(new ParallelComputer(true, true), cls);  
    } 

    public static class ParallelTest1 { 
     @Test public void a(){} 
     @Test public void b(){} 
    } 

    public static class ParallelTest2 { 
     @Test public void a(){} 
     @Test public void b(){} 
    } 
} 
+1

嗨,這真的很有幫助。但是,即使我有更多的班級,也能夠一次只並行運行4個班級。對沒有並行運行的類是否有任何限制? – Santoshsarma 2012-07-11 05:45:38

+12

如果我不想列出每一個測試課程(這看起來像是一個巨大的痛苦)會怎麼樣?是否有辦法讓它自動拾取每個課程並且並行運行它們? – 2014-05-19 21:50:35

+1

有用但請注意,測試例外不會自動拋出。你需要檢查'runClasses'的結果。 – 2015-03-19 16:20:00

-10

下面是一些示例代碼。這對我來說真的很好。 ExecutorService的。

public class TestCases { 
    static ExecutorService exe ; 
    public static void main(String[] args) throws Throwable { 
     test1() ; 
     test2() ; 
     test3() ; 
    } 
    public static void test1() { 
     exe = Executors.newCachedThreadPool() ; 
     for (int i = 0 ; i < 10 ; i++) { 
      Test1 test1 = new Test1() ; 
      exe.execute(test1) ; 
     } 
     exe.shutdown() ; 
     while(!exe.isShutDown()) { 
     } 
    } 
    //same for test2 and test3 
} 

public class Test1 implements Runnable { 
    public Test1() { 
    } 
    @Test 
    public myTest throws Throwable { 
    } 
}