0
0
JUnittesting~10 mins

@Execution annotation in JUnit - Test Execution Trace

Choose your learning style9 modes available
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.

Test Code - JUnit 5
JUnit
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);
    }
}
Execution Trace - 6 Steps
StepActionSystem StateAssertionResult
1JUnit test runner starts the ParallelExecutionTest classTest class loaded with @Execution(ExecutionMode.CONCURRENT) annotation-PASS
2JUnit identifies testOne() method and schedules it for executiontestOne() ready to run concurrently-PASS
3JUnit identifies testTwo() method and schedules it for execution concurrently with testOne()testTwo() ready to run concurrently-PASS
4testOne() executes: sleeps 100ms then asserts truetestOne() runningassertTrue(true) verifies condition is truePASS
5testTwo() executes concurrently: sleeps 100ms then asserts truetestTwo() runningassertTrue(true) verifies condition is truePASS
6JUnit completes both tests and reports resultsBoth tests finished successfullyBoth assertions passedPASS
Failure Scenario
Failing Condition: If the @Execution annotation is missing or set to ExecutionMode.SAME_THREAD, tests run sequentially, not concurrently as expected.
Execution Trace Quiz - 3 Questions
Test your understanding
What does the @Execution(ExecutionMode.CONCURRENT) annotation do in this test?
ARuns test methods one after another sequentially
BRuns test methods in parallel threads
CDisables all tests in the class
DRuns tests only on the main thread
Key Result
Using @Execution(ExecutionMode.CONCURRENT) allows tests to run in parallel, improving test suite speed. Always verify the annotation is present to enable concurrency.