Sunday, September 18, 2011

Speeding up Unit Tests by running them in parallel

I just discovered an interesting parameter in the maven-surefire-plugin when using JUnit 4.7+, that tests can be executed in parallel. With multi-threaded CPUs, OS and the like, this helps a lot when you want to decrease the time of your test suites.

So, what are the configurations options that you have:
  1. Running test methods in parallel:
    <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.9</version>
    <configuration>
    <parallel>methods</parallel>
    </configuration>
    </plugin>

  2. Running test classes in parallel:
    <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.9</version>
    <configuration>
    <parallel>classes</parallel>
    </configuration>
    </plugin>

There are some things to take care when running unit tests in parallel. Some of them might not be independent, isolated and reproducible. There are times when you have some test methods that might depend on other methods in the test class. That time you should use the parallel test class execution. You may also want to tweak the number of threads and core on which these threads run, using this configuration:

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.9</version>
<configuration>
<parallel>methods</parallel>
<threadCount>4</threadCount>
<perCoreThreadCount>true</perCoreThreadCount>
</configuration>
</plugin>

No comments: