【问题标题】:How to make JUnit test cases execute in parallel? [duplicate]如何让 JUnit 测试用例并行执行? [复制]
【发布时间】:2011-07-28 14:19:12
【问题描述】:

可能重复:
Running junit tests in parallel?

发现jUnit里面的测试用例是按顺序执行的,如何让它们并行执行?

【问题讨论】:

    标签: junit


    【解决方案1】:

    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(){}  
       }  
    } 
    

    【讨论】:

    • 嗨,这真的很有帮助。但是,即使我在数组中有更多类,一次只能并行运行 4 个类。并行运行的类有没有限制?
    • 如果我不想列出每个测试类怎么办(这似乎是一个巨大的痛苦)?有没有办法让它自动拾取每个类并并行运行它们?
    • 有用,但请注意测试中的异常不会自动抛出。你需要检查runClasses的结果。
    • 这在 JUnit5 上运行时不起作用。我得到了长时间运行的测试(5-6 秒),并且当像这样并行执行时,测试在 100 毫秒后退出。我还测试了这个确切的代码,结果相同。所有测试都调用 System.out.println(...),我看不到任何输出。
    • 这不会生成从 test() 内部并行运行的类的结果。
    【解决方案2】:

    这里是一些示例代码。这对我来说真的很好。执行器服务。

    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 {
        }
    }
    

    【讨论】:

    • 根本不是问题所要问的。
    猜你喜欢
    • 2018-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-06
    • 1970-01-01
    • 2019-01-29
    • 2013-07-22
    • 1970-01-01
    相关资源
    最近更新 更多