Skip to content
javahacks.dev
JUnit

JUnit 5 Lifecycle Annotations and Execution Order Explained

See when BeforeAll, BeforeEach, AfterEach and AfterAll run, how nested classes and instance lifecycles change that order and how to control test order.

7 min read
Summarize in AI
Flat illustration of a JUnit test run with one failing test, with the JUnit5, Cucumber, Selenium, GitHub Actions and Jenkins logos.

Shared state between tests is the most common cause of a test that passes alone and fails in the suite. Knowing exactly when JUnit creates the instance and when each callback runs makes that class of bug easy to find. The example below prints the sequence; the output is deterministic for this class. The framework overview is in the JUnit 5 handbook.

The sequence

LifecycleTest.javajava
class LifecycleTest {

    @BeforeAll  static void beforeAll()  { System.out.println("beforeAll"); }
    @BeforeEach void beforeEach()        { System.out.println("  beforeEach " + hashCode()); }
    @Test       void first()             { System.out.println("    first"); }
    @Test       void second()            { System.out.println("    second"); }
    @AfterEach  void afterEach()         { System.out.println("  afterEach"); }
    @AfterAll   static void afterAll()   { System.out.println("afterAll"); }
}

The output has this shape (the order of first and second can differ, and the hash codes will):

Text
beforeAll
  beforeEach 1355531311
    first
  afterEach
  beforeEach 1219012930
    second
  afterEach
afterAll

Two things stand out. beforeAll and afterAll bracket the whole class, and each test runs between a fresh beforeEach and afterEach. The hash codes differ because JUnit created a new LifecycleTest for each method, which is the default PER_METHOD lifecycle. A field set in first() is gone in second().

PER_CLASS: one instance for all tests

java
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class ExpensiveSetupTest {

    private Server server;

    @BeforeAll
    void start() { server = Server.start(); }      // not static

    @AfterAll
    void stop() { server.stop(); }
}

With one instance per class, @BeforeAll and @AfterAll can be instance methods, and fields persist across tests, so tests can influence each other. Use it for read-only expensive fixtures and keep any mutable field reset in @BeforeEach. A shared instance is also what makes @Nested classes use @BeforeAll.

Inheritance and nesting

For a class hierarchy, setup runs from the superclass down and teardown from the subclass up:

Text
Base.beforeAll → Child.beforeAll → Base.beforeEach → Child.beforeEach → test
→ Child.afterEach → Base.afterEach → Child.afterAll → Base.afterAll

For @Nested classes, the outer @BeforeEach runs first, then the nested one, then the test. Nested test classes cannot have static members (until Java 16 they could not at all), so a @BeforeAll inside needs the PER_CLASS lifecycle on the nested class.

Parameterized and repeated tests

For @ParameterizedTest, @BeforeEach and @AfterEach run around every invocation, not once per method. @RepeatedTest(3) does the same for each repetition. That makes the setup cost multiply with the number of cases.

Test method order

JUnit sorts test methods by a deterministic algorithm based on the method name hash, so the order is stable between runs and intentionally not intuitive. If tests depend on order, they depend on shared state. For a real sequential scenario, such as a lifecycle test of a resource, declare it:

java
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class OrderedTest {
    @Test @Order(1) void create() { }
    @Test @Order(2) void read() { }
}

Prefer a single test that does the sequence, which cannot be run out of order. Class order can be controlled in junit-platform.properties with junit.jupiter.testclass.order.default.

Extensions wrap the annotations

Everything above treats @BeforeEach as the first thing that runs around a test. Extensions run outside it. A callback such as BeforeEachCallback runs before the annotated methods and its AfterEachCallback runs after them, which is why a Spring or Mockito extension can prepare a context that your own setup method then uses. This test records the order, including a base class with its own callbacks.

OrderOfEvents.javajava
@ExtendWith(OrderOfEvents.Trace.class)
class OrderOfEvents {

    static class Trace implements BeforeAllCallback, BeforeEachCallback, AfterEachCallback, AfterAllCallback {
        public void beforeAll(ExtensionContext c) { System.out.println("extension beforeAll"); }
        public void beforeEach(ExtensionContext c) { System.out.println("  extension beforeEach"); }
        public void afterEach(ExtensionContext c) { System.out.println("  extension afterEach"); }
        public void afterAll(ExtensionContext c) { System.out.println("extension afterAll"); }
    }

    @BeforeAll static void beforeAll() { System.out.println("@BeforeAll"); }
    @BeforeEach void beforeEach() { System.out.println("  @BeforeEach on instance " + System.identityHashCode(this) % 1000); }
    @AfterEach void afterEach() { System.out.println("  @AfterEach"); }
    @AfterAll static void afterAll() { System.out.println("@AfterAll"); }

    @Test void first() { System.out.println("    test first"); }
    @Test void second() { System.out.println("    test second"); }
}
Text
extension beforeAll
@BeforeAll
  extension beforeEach
  @BeforeEach on instance 395
    test second
  @AfterEach
  extension afterEach
  extension beforeEach
  @BeforeEach on instance 187
    test first
  @AfterEach
  extension afterEach
@AfterAll
extension afterAll

Three facts are visible in that output, all run on JUnit 6.0.0. The extension callbacks bracket the annotated ones on the way in and the way out. Each test ran on a different instance (395, then 187), which is why a field written in one test is not visible in the next. And second ran before first: the default method order is deterministic, derived from a hash of the method name, but it is deliberately not the order in the file. A test suite that passes only when first runs first has a shared state bug, and this is the setting that exposes it.

Share expensive setup without sharing state

Creating a Testcontainers database or a Spring context per test is slow, and creating one per class is usually enough. A static container started in @BeforeAll or a static field annotated with @Container serves every test in the class. What must not be shared is the data. Reset it in @BeforeEach, or give each test its own rows.

java
@Testcontainers
class OrderRepositoryTest {

    @Container
    static PostgreSQLContainer<?> db = new PostgreSQLContainer<>("postgres:17-alpine");

    JdbcTemplate jdbc;

    @BeforeEach
    void cleanTables() {
        jdbc = new JdbcTemplate(dataSource(db));
        jdbc.execute("TRUNCATE orders RESTART IDENTITY CASCADE");
    }
}

The container is started once, the tables are emptied before every test, and any test can run alone or in any order. If a test needs rows another test created, move the shared creation into the @BeforeEach of both, instead of relying on the order.

Per-test temporary files

@TempDir is a lifecycle feature too. A @TempDir field on a non-static member gives each test a fresh directory that is deleted afterwards, and a static one gives one directory for the whole class. Pick by what the test mutates.

java
@Test
void writesTheReport(@TempDir Path dir) throws IOException {
    Path report = dir.resolve("report.csv");
    new ReportWriter().write(report, List.of("a,1", "b,2"));
    assertThat(Files.readAllLines(report)).containsExactly("a,1", "b,2");
}

The directory is removed after the test even when it fails, so a failed run leaves nothing behind to break the next one, and parallel runs cannot collide on a hard coded path such as /tmp/report.csv.

The lifecycle questions that cause real bugs

Most lifecycle trouble comes from three habits. Putting a mutable object in an instance field and assuming it persists, which is wrong under the default lifecycle. Using @TestInstance(PER_CLASS) for convenience and then leaking state between tests, which is correct only if you reset it. And relying on @Order to build a story across tests, which makes the failure of the first test produce failures in the next ten and hides the cause. Keep each test independent, put what is expensive in a class-level resource, and put what is cheap in @BeforeEach.

Where lifecycle bugs hide in practice

The lifecycle matters most when a suite grows. In a small project every test passes in the order the author wrote it, and nobody notices a dependency between two of them. When the suite reaches a few hundred tests and a CI runner executes classes in parallel, the same hidden dependency turns into a failure that appears once in twenty runs and disappears when rerun. The first step is to run the suite with a random method order and parallel execution enabled in a branch, and read which tests fail.

src/test/resources/junit-platform.propertiesproperties
junit.jupiter.testmethod.order.default=org.junit.jupiter.api.MethodOrderer$Random
junit.jupiter.execution.parallel.enabled=true
junit.jupiter.execution.parallel.mode.default=same_thread
junit.jupiter.execution.parallel.mode.classes.default=concurrent

The random orderer prints its seed at the start of the run so a failing order can be reproduced. Classes run concurrently but methods inside each class stay on one thread, which is the setting least likely to break a suite that was not written for parallelism. Each failure that appears points at shared state: a static field, a fixed file path, a table that two classes both fill, a clock. Fix those, one test at a time, and keep the random order on permanently so the dependencies cannot return.

Where this does not apply

Extensions add callbacks of their own (BeforeEachCallback, ParameterResolver) that run at defined points around these. The Spring TestContext framework, for example, prepares the context before @BeforeEach. Assertions that fail clearly are the subject of readable assertions, and the first project is in the JUnit 5 tutorial. The JUnit user guide on test classes and methods and the extension lifecycle chapter give the exact order. For failures caused by shared state, see the testing strategy.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.