How to run junit tests in 1 jvm but with multiple threads?

Short story: the maven-surefire-plugin has a configuration like

<parallel>methods</parallel>
<threadCount>4</threadCount>

to run junit tests in 1 jvm with 4 threads. Does gradle have anything similar?

Long story: my junit tests clean a special db (not rdbms), write stuff to it, wait a bit for the db to do its job and finally read from the db to verify. Not more than 1 test can run with a db at any time. Running all the junit tests sequentially takes about 1 hour. So I think I’ll create 4 instances of that db, have 4 java locks, loop forever in the @Before method to get any free db lock and release the lock in @After. Because of using those locks, Gradle’s maxParallelForks doesn’t work for me as tests run in different jvms.

How could I do it in Gradle?

Regards.

I don’t think Gradle itself has something similar to that.

But if you are on JUnit 5, you can configure it to execute tests in parallel within the same JVM. Gradle should support that.

A different solution that also works for JUnit 4 is to use maxParallelForks = 4 like you suggested and then listen on the system property org.gradle.test.worker in the test. That will give you the worker ID, which is apparently just number starting from 1 that increments each time a worker is started. So you can use something like Integer.getInteger("org.gradle.test.worker") % 4 in the test to get a value from 1-4 for each forked process that you can then use to connect to the corresponding db instance without the need to synchronize or poll for an available connection.