0
0
JUnittesting~5 mins

@Execution annotation in JUnit

Choose your learning style9 modes available
Introduction

The @Execution annotation tells JUnit how to run tests: either all at once or one by one. This helps control test speed and resource use.

When you want tests to run in parallel to finish faster.
When tests share data and must run one after another to avoid conflicts.
When debugging a test that fails only if run with others.
When running many tests and you want to speed up the process.
Syntax
JUnit
@Execution(ExecutionMode.CONCURRENT)
// or
@Execution(ExecutionMode.SAME_THREAD)

@Execution is placed on a test class or test method.

ExecutionMode.CONCURRENT runs tests in parallel.

ExecutionMode.SAME_THREAD runs tests one by one.

Examples
This runs testOne and testTwo at the same time.
JUnit
@Execution(ExecutionMode.CONCURRENT)
public class MyTests {
    @Test
    void testOne() {}
    @Test
    void testTwo() {}
}
This runs testOne and testTwo one after another.
JUnit
@Execution(ExecutionMode.SAME_THREAD)
public class MyTests {
    @Test
    void testOne() {}
    @Test
    void testTwo() {}
}
Sample Program

This test class runs testA and testB at the same time. Both print start and end messages with a half-second pause.

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 SampleExecutionTest {

    @Test
    void testA() throws InterruptedException {
        System.out.println("Start testA");
        Thread.sleep(500);
        System.out.println("End testA");
    }

    @Test
    void testB() throws InterruptedException {
        System.out.println("Start testB");
        Thread.sleep(500);
        System.out.println("End testB");
    }
}
OutputSuccess
Important Notes

Parallel tests can speed up testing but may cause issues if tests share data.

Use @Execution carefully to avoid flaky tests.

Summary

@Execution controls if tests run together or one by one.

Use ExecutionMode.CONCURRENT for faster parallel tests.

Use ExecutionMode.SAME_THREAD to avoid conflicts in shared data.