Custom test fork action

There’s times where I’d like to perform an action for each test fork, for example give each fork a unique port number that can be referenced in the tests to avoid clashes with other forks.

Currently the only way I’ve found to do this is to extend the Test class and override copyTo(JavaForkOptions target)

Eg:

public class Test2 extends org.gradle.api.tasks.testing.Test {
    private final AtomicInteger nextPort = new AtomicInteger(9000); 
    public Test copyTo(JavaForkOptions target) {
        super.copyTo(target);
        target.systemProperty("port", nextPort.getAndIncrement());
        return this;
    }
}

This works but requires me to disable the default Test task and configure a Test2 task instance.

I’d like to request the following method added to Test task.

public void beforeFork(Action<JavaForkOptions> action) 

This would make it much cleaner

apply plugin: 'java' 
test {
    def nextPort = new AtomicInteger(9000); 
    beforeFork { target ->
        target.systemProperty("port", nextPort.getAndIncrement())
    } 
} 

Related Stack Overflow Q&A here

1 Like

This didn’t works for me.
When I ran my test2 task, for every test class it gives me same port. I have 2 test classes to be run in parallel.

Here is my configuration:

Command I use to run : gradle test2

Did I miss something?

You’ll have to set forkEvery eg

task test2(Type: Test2){
   forkEvery = 1
   ... 
}