Run JUnit tests in parallel using maven Surefire plugin

In most of cases parallel execution of tests is recommended, this option reduces time needed to execute tests and gives quick feedback on build state. On the other hand it should be used wisely since parallel execution of test can impact memory state and slow down execution instead of desired 'speed-up'. In the example below we are going to consider one of the options of parallel test run.

Let's take a look at how we can run JUnit tests in parallel using maven Surefire plugin. We are going to run test methods in parallel. Other available options are classes, both classes and methods, suites, suitesAndClasses, suitesAndMethods, classesAndMethods or all. We will stick to 'methods'. To make the example more "visual" we will use Selenium WebDriver. For the sake of simplicity each JUnit test method only opens a browser and after 3 seconds pause closes the browser. Add Maven Surefire Plugin to your pom.xml:
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.19.1</version>
    <configuration>
        <parallel>methods</parallel>
        <threadCount>3</threadCount>
    </configuration>
</plugin>

Now we need to add dependencies for Selenium and JUnit:
<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.12</version>
</dependency>
<dependency>
  <groupId>org.seleniumhq.selenium</groupId>
  <artifactId>selenium-java</artifactId>
  <version>2.53.0</version>
</dependency>

After that we need to add test class and test methods:
public class AppTest {

    private void navigateWaitAndClose(String target) {
        WebDriver driver = new FirefoxDriver();
        driver.get(target);

        // wouldn't recommend Thread.sleep real project, 
        // it's only for demo purposes to keep the browser open a few seconds :)
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        driver.quit();
    }

    @Test
    public void simpleTestMethod() {
        navigateWaitAndClose("http://olyv-qa.blogspot.com/");
    }

    //place some more test methods
}

Please note: AppTest class doesn't extend TestCase class.

Now you can run your test with mvn test command. And that's simply it!   

Comments