32

Possible Duplicate:
Running junit tests in parallel?

I found the test cases inside jUnit are executed in sequence, how to make them execute in parallel?

Community
  • 1
  • 1
user496949
  • 83,087
  • 147
  • 309
  • 426

2 Answers2

37

Junit4 provides parallel feature using 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(){}  
   }  
} 
cheffe
  • 9,345
  • 2
  • 46
  • 57
卢声远 Shengyuan Lu
  • 31,208
  • 22
  • 85
  • 130
  • 1
    Hi, This is really helpful. but, able to run 4 classes only in parallel at a time even though I've more classes in array. Is there any limitation on no of classes running in parallel ? – Santoshsarma Jul 11 '12 at 05:45
  • 12
    What if I don't want to list every single test class (that's seems like a huge pain)? Is there a way to have it pick up every class automatically and run them in parallel? – Christopher Perry May 19 '14 at 21:50
  • 1
    Useful but note that exceptions from tests do not get automatically thrown. You need to check the result of `runClasses`. – Justin Harris Mar 19 '15 at 16:20
  • 1
    This doesn't work when running on JUnit5. I got long running tests (5-6 sec), and when executing like this in parallell, the tests exit after 100ms. I also tested this exact code, with same results. All tests calls System.out.println(...), and I see no output. – Yngvar Kristiansen Sep 18 '16 at 05:50
  • This won't generate the results of the classes being run in parallel from inside test(). – d_void Mar 10 '20 at 06:56
-13

Here is some sample code. This works for me really well. 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 {
    }
}
Sears India
  • 210
  • 1
  • 6