Test Overview
This test demonstrates how to use the @Execution annotation in JUnit 5 to control the execution mode of test methods within a test class. It verifies that tests run in the specified concurrent mode.
This test demonstrates how to use the @Execution annotation in JUnit 5 to control the execution mode of test methods within a test class. It verifies that tests run in the specified concurrent mode.
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; import static org.junit.jupiter.api.Assertions.assertTrue; @Execution(ExecutionMode.CONCURRENT) public class ParallelExecutionTest { @Test void testOne() throws InterruptedException { Thread.sleep(100); // Simulate work assertTrue(true); } @Test void testTwo() throws InterruptedException { Thread.sleep(100); // Simulate work assertTrue(true); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | JUnit test runner starts the ParallelExecutionTest class | Test class loaded with @Execution(ExecutionMode.CONCURRENT) annotation | — | PASS |
| 2 | JUnit identifies testOne() method and schedules it for execution | testOne() ready to run concurrently | — | PASS |
| 3 | JUnit identifies testTwo() method and schedules it for execution concurrently with testOne() | testTwo() ready to run concurrently | — | PASS |
| 4 | testOne() executes: sleeps 100ms then asserts true | testOne() running | assertTrue(true) verifies condition is true | PASS |
| 5 | testTwo() executes concurrently: sleeps 100ms then asserts true | testTwo() running | assertTrue(true) verifies condition is true | PASS |
| 6 | JUnit completes both tests and reports results | Both tests finished successfully | Both assertions passed | PASS |
@Execution annotation in JUnit?@Execution annotation controls how tests are run: either all at once (concurrently) or one after another (sequentially).@Order, @Disabled, or @Timeout.@Execution in JUnit?ExecutionMode.CONCURRENT and ExecutionMode.SAME_THREAD. There is no SEQUENTIAL or PARALLEL mode.ExecutionMode.CONCURRENT runs tests in parallel threads.@Execution(ExecutionMode.CONCURRENT)
class SampleTest {
@Test void testA() { System.out.println("A"); }
@Test void testB() { System.out.println("B"); }
@Test void testC() { System.out.println("C"); }
}@Execution(ExecutionMode.CONCURRENT), tests run in parallel threads, so their output order is not guaranteed.@Execution:
@Execution(ExecutionMode.CONCURRENT)
class TestExample {
private int counter = 0;
@Test
void increment() {
counter++;
assertEquals(1, counter);
}
@Test
void decrement() {
counter--;
assertEquals(-1, counter);
}
}counter variable is shared and modified by both tests without synchronization.@Execution to optimize test speed while avoiding conflicts?@Execution(ExecutionMode.SAME_THREAD) on tests with shared data, and CONCURRENT on others to speed up execution.Pass the test and this pattern moves unknown