如何使JUnit测试用例并行执行?

如何使JUnit测试用例并行执行?,junit,Junit,可能重复: 我发现jUnit中的测试用例是按顺序执行的,如何使它们并行执行?Junit4使用并行计算机提供了并行功能: 公共类并行计算机测试{ @试验 公共无效测试(){ 类[]cls={ParallelTest1.Class,ParallelTest2.Class}; //类间平行 JUnitCore.runClasses(ParallelComputer.classes(),cls); //类中方法之间的并行 JUnitCore.runClasses(ParallelComputer.me

可能重复:


我发现jUnit中的测试用例是按顺序执行的,如何使它们并行执行?

Junit4使用并行计算机提供了并行功能:

公共类并行计算机测试{
@试验
公共无效测试(){
类[]cls={ParallelTest1.Class,ParallelTest2.Class};
//类间平行
JUnitCore.runClasses(ParallelComputer.classes(),cls);
//类中方法之间的并行
JUnitCore.runClasses(ParallelComputer.methods(),cls);
//并行所有类中的所有方法
runClasses(新的并行计算机(true,true),cls);
} 
公共静态类ParallelTest1{
@测试公共void a(){}
@测试公共void b(){}
}  
公共静态类ParallelTest2{
@测试公共void a(){}
@测试公共void b(){}
}  
} 

以下是一些示例代码。这对我很有效。执行人服务

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 {
    }
}
公共类测试用例{
静态执行器服务;
公共静态void main(字符串[]args)抛出可丢弃的{
test1();
test2();
test3();
}
公共静态void test1(){
exe=Executors.newCachedThreadPool();
对于(int i=0;i<10;i++){
Test1 Test1=新的Test1();
execute(test1);
}
exe.shutdown();
而(!exe.isshutton()){
}
}
//test2和test3也是如此
}
公共类Test1实现了Runnable{
公共测试1(){
}
@试验
公共myTest可丢弃{
}
}

您好,这真的很有帮助。但是,即使我在数组中有更多的类,一次只能并行运行4个类。并行运行的类的数量有限制吗?如果我不想列出每一个测试类(这似乎是一个巨大的痛苦),该怎么办?有没有办法让它自动拾取每个类并并行运行它们?这很有用,但请注意,测试中的异常不会自动抛出。您需要检查
runClasses
的结果。在JUnit5上运行时,这不起作用。我得到了长时间运行的测试(5-6秒),当以并行方式执行时,测试将在100毫秒后退出。我还测试了这段代码,得到了相同的结果。所有测试都调用System.out.println(…),我看不到任何输出。这不会生成从内部测试()并行运行的类的结果。这根本不是问题所在。