Dark theme | Light theme

November 10, 2010

Gradle Goodness: Running Tests in Parallel

Once we apply the Java plugin we can run our tests with the test task. Normally each test is run sequentially, but we can also run tests in parallel. This speeds up the test task considerably especially with a lot of tests. We set the property maxParallelForks to a number greater than 1 to enable parallel tests.

We can also set the additional property forkEvery on the test task. With this property we define how many tests should run in a parallel test fork.

In the following build script we first create a lot of tests with the createTests task and then we can run them with the test task. We can pass the properties maxParallelForks and forkEvery to play around and see what happens. Of course we can also use hard coded values in our build script for the test task properties.

apply plugin: 'java'

repositories {

dependencies {
    testCompile 'junit:junit:4.8.2'

test {
    if (project.hasProperty('maxParallelForks')) 
        maxParallelForks = project.maxParallelForks as int
    if (project.hasProperty('forkEvery')) 
        forkEvery = project.forkEvery as int

packages = 10
tests = 30

task createTests << {
    (0..packages).each { packageCounter ->
        def packageName = "gradletest${packageCounter}"
        (0..tests).each { classCounter ->
            def testClassName = "Gradle${classCounter}Test"
            copy {
                from 'src/templates'
                into 'src/test/java'
                expand([packageName: packageName, testClassName: testClassName])
                rename '(.*).java', packageName + '/' + testClassName + '.java'
                include ''
// File: src/templates/
package ${packageName};

import org.junit.Test;
import static org.junit.Assert.*;

public class ${testClassName} {

    public void testString() throws Exception {
        assertEquals("mrhaki", "mr" + "haki");

So first we create the tests: $ gradle createTests. And then we can experiment with different options:

$ gradle clean test

Total time: 1 mins 33.942 secs

$ gradle clean test -PmaxParallelForks=10

Total time: 36.68 secs

$ gradle clean test -PmaxParallelForks=4 -PforkEvery=25

Total time: 56.066 secs

Written with Gradle 0.9.