JUnit: Run simultaneous tests

kmccoy picture kmccoy · Feb 18, 2011 · Viewed 7.9k times · Source

I am still fairly new to Java programming and to JUnit testing. I use NetBeans 6.9.1 which comes with junit-4.5 (but I have added junit-4.8.2 to my library).

I have a number of test classes and in each class there are a number of @Test methods.

When I run a particular Test class it runs through each @Test method one at a time. I have also created a Test Suite with

@RunWith(Suite.class)
@Suite.SuiteClasses(value = {
    TestClassA.class,
    TestClassB.class,
    TestClassC.class})
public class NewTestSuite {
}

which will run through each of my Test Classes and within each run each @Test method.

My question is: is it possible for me to run the Test Classes simultaneously? Or, within each Test Class is it possible to run the @Test methods simultaneously?

Doing so would allow me to run through all of the tests much faster than having the classes and methods run one-at-a-time.

Thanks!

Answer

卢声远 Shengyuan Lu picture 卢声远 Shengyuan Lu · Feb 18, 2011

Use org.junit.experimental.ParallelComputer: Sample:

    public class NewTestSuite {

       public static void main(String[] s){

         Class[] cls={TestClassA.class,TestClassB.class,TestClassB.class };  

         //simultaneously all methods in all classes  
         Result result = JUnitCore.runClasses(new ParallelComputer(true, true), cls);
         System.out.print(result.wasSuccessful());

         //simultaneously among classes  
         //Result result = JUnitCore.runClasses(ParallelComputer.classes(), cls);  

         //simultaneously among methods in a class  
         //Result result = JUnitCore.runClasses(ParallelComputer.methods(), cls);  
      }
   }