Running tests in parallel saves time by checking many things at once instead of one by one.
Parallel test configuration in JUnit
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; @Execution(ExecutionMode.CONCURRENT) public class MyParallelTests { @Test void testOne() { // test code here } @Test void testTwo() { // test code here } }
Use @Execution(ExecutionMode.CONCURRENT) on the test class or method to enable parallel execution.
JUnit 5 supports parallel execution natively with this annotation and configuration.
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; @Execution(ExecutionMode.CONCURRENT) public class ParallelTests { @Test void testA() { // test A code } @Test void testB() { // test B code } }
testX runs in parallel; testY runs normally.import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; public class MixedTests { @Test @Execution(ExecutionMode.CONCURRENT) void testX() { // test X runs in parallel } @Test @Execution(ExecutionMode.SAME_THREAD) void testY() { // test Y runs sequentially } }
This test class runs two tests at the same time. Each test waits 1 second. Running in parallel means total time is about 1 second, not 2.
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; @Execution(ExecutionMode.CONCURRENT) public class SampleParallelTest { @Test void testOne() throws InterruptedException { System.out.println("Start testOne"); Thread.sleep(1000); System.out.println("End testOne"); } @Test void testTwo() throws InterruptedException { System.out.println("Start testTwo"); Thread.sleep(1000); System.out.println("End testTwo"); } }
Make sure tests do not share or change the same data to avoid conflicts when running in parallel.
You can configure parallelism level in JUnit platform properties if needed.
Parallel tests help speed but can make debugging harder if tests interfere.
Parallel test configuration runs tests at the same time to save time.
Use @Execution(ExecutionMode.CONCURRENT) to enable parallel tests in JUnit.
Ensure tests are independent to avoid errors when running in parallel.