2011-04-03 117 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 { 
    } 
}