JUnit 5 Lifecycle Annotations: @BeforeAll, @AfterEach, and Test Instance Modes

JUnit 5 Lifecycle Annotations: @BeforeAll, @AfterEach, and Test Instance Modes

JUnit 5 lifecycle annotations control when setup and teardown code runs relative to your tests. @BeforeAll and @AfterAll run once per class (must be static by default). @BeforeEach and @AfterEach run around every test. The PER_CLASS lifecycle mode removes the static requirement and lets you share expensive resources across tests in the same class. This post covers all four annotations, the two instance modes, and the execution order you need to know.

Every test class in JUnit 5 has a lifecycle: instances are created, setup code runs, tests execute, teardown code runs. Getting this right is the difference between fast, reliable tests and slow, flaky ones. Get the lifecycle wrong and you'll either rebuild expensive resources for every test (slow) or leak state between tests (flaky).

The Four Lifecycle Annotations

JUnit 5 provides four annotations that hook into the test execution lifecycle:

Annotation When it runs Static by default
@BeforeAll Once before any test in the class Yes (with PER_METHOD)
@BeforeEach Before each test method No
@AfterEach After each test method No
@AfterAll Once after all tests in the class Yes (with PER_METHOD)

If you've used JUnit 4, these replace @BeforeClass, @Before, @After, and @AfterClass.

@BeforeEach and @AfterEach

These are the most commonly used. @BeforeEach runs before every single test method in the class:

class OrderServiceTest {

    private OrderService service;
    private OrderRepository repository;

    @BeforeEach
    void setUp() {
        repository = mock(OrderRepository.class);
        service = new OrderService(repository);
    }

    @AfterEach
    void tearDown() {
        // release resources, reset state
        verifyNoMoreInteractions(repository);
    }

    @Test
    void createOrder_shouldPersistToRepository() {
        Order order = new Order("ITEM-001", 2);
        service.create(order);
        verify(repository).save(order);
    }

    @Test
    void createOrder_withInvalidQuantity_shouldThrow() {
        assertThrows(InvalidQuantityException.class,
            () -> service.create(new Order("ITEM-001", -1)));
    }
}

Each test gets a fresh OrderService and OrderRepository mock. Tests are isolated from each other — one test's mock expectations don't bleed into the next.

The @AfterEach here calls verifyNoMoreInteractions, which is a Mockito pattern that fails the test if any unexpected calls were made. Running this in @AfterEach means it applies to every test without repeating it.

@BeforeAll and @AfterAll

@BeforeAll runs once before any test in the class. Under the default PER_METHOD lifecycle, it must be static:

class DatabaseIntegrationTest {

    private static DataSource dataSource;
    private static Connection connection;

    @BeforeAll
    static void setUpDatabase() {
        dataSource = H2DataSourceFactory.createInMemoryDataSource();
        connection = dataSource.getConnection();
        runMigrations(connection);
    }

    @AfterAll
    static void tearDownDatabase() {
        connection.close();
    }

    @BeforeEach
    void startTransaction() {
        connection.setAutoCommit(false);
    }

    @AfterEach
    void rollbackTransaction() {
        connection.rollback();
    }

    @Test
    void insertUser_shouldBeQueryable() {
        // insert and query
    }

    @Test
    void deleteUser_shouldNotBeQueryable() {
        // delete and verify
    }
}

The database starts once (@BeforeAll). Each test gets a transaction that's rolled back (@BeforeEach + @AfterEach). This is fast and gives each test a clean database state without rebuilding the whole schema.

Why static? Because JUnit creates a new instance of the test class for each test method under the default lifecycle. A non-static @BeforeAll would run once per instance — which means once per test — defeating the purpose. By requiring static, JUnit 5 makes this explicit.

PER_CLASS Lifecycle Mode

The static requirement for @BeforeAll is limiting when you want to share expensive state that isn't easily stored in static fields (for example, when your resource holds references to this, or when you're working with frameworks that depend on instance state).

@TestInstance(Lifecycle.PER_CLASS) tells JUnit to create one test class instance and reuse it for all tests:

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class ElasticsearchIntegrationTest {

    private ElasticsearchContainer elasticsearch;
    private RestHighLevelClient client;

    @BeforeAll
    void startElasticsearch() {
        elasticsearch = new ElasticsearchContainer("elasticsearch:8.11.0");
        elasticsearch.start();
        client = buildClient(elasticsearch.getHttpHostAddress());
    }

    @AfterAll
    void stopElasticsearch() {
        client.close();
        elasticsearch.stop();
    }

    @BeforeEach
    void clearIndex() {
        client.indices().delete(new DeleteIndexRequest("test-index"), RequestOptions.DEFAULT);
        client.indices().create(new CreateIndexRequest("test-index"), RequestOptions.DEFAULT);
    }

    @Test
    void indexDocument_shouldBeSearchable() { ... }

    @Test
    void deleteDocument_shouldNotBeReturned() { ... }
}

With PER_CLASS:

  • @BeforeAll doesn't need to be static
  • All tests share the same instance fields
  • One container start/stop instead of one per test
  • But: tests can share mutable state (by design or accidentally)

The tradeoff is explicit. PER_CLASS is the right choice for integration tests with expensive startup (Testcontainers, embedded servers, gRPC channels). PER_METHOD (default) is right for unit tests where isolation matters more than startup speed.

Execution Order in Detail

Knowing the exact execution order matters when debugging test interactions. Here's what happens for a class with two test methods:

PER_METHOD (default):

new TestClass()  →  @BeforeAll (static)
  new TestClass()  →  @BeforeEach  →  test1  →  @AfterEach
  new TestClass()  →  @BeforeEach  →  test2  →  @AfterEach
@AfterAll (static)

Two instances of the test class are created, one per test.

PER_CLASS:

new TestClass()  →  @BeforeAll (non-static)
  @BeforeEach  →  test1  →  @AfterEach
  @BeforeEach  →  test2  →  @AfterEach
@AfterAll (non-static)

One instance throughout.

Execution Order with @Nested

When you combine lifecycle annotations with @Nested classes, the outer class's setup always runs before the inner class's setup:

class OuterTest {

    @BeforeEach
    void outerSetup() { System.out.println("outer setup"); }

    @AfterEach
    void outerTeardown() { System.out.println("outer teardown"); }

    @Nested
    class InnerTest {

        @BeforeEach
        void innerSetup() { System.out.println("inner setup"); }

        @AfterEach
        void innerTeardown() { System.out.println("inner teardown"); }

        @Test
        void test() { System.out.println("test"); }
    }
}

Output:

outer setup
inner setup
test
inner teardown
outer teardown

Outer wraps inner. This is how you build up context layer by layer in nested test hierarchies.

Multiple @BeforeEach Methods

You can have more than one @BeforeEach method in a class. JUnit 5 runs them all, but the order between them is not guaranteed:

@BeforeEach
void setUpDatabase() { ... }

@BeforeEach
void setUpMocks() { ... }

If the order matters, use a single @BeforeEach that calls other methods explicitly:

@BeforeEach
void setUp() {
    setUpDatabase();
    setUpMocks();
}

This is clearer about ordering and easier to read.

@BeforeAll for Test Data Loading

A common pattern for integration tests: load test data once in @BeforeAll, then run read-only tests that don't modify it:

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class ProductCatalogTest {

    private ProductRepository repository;
    private List<Product> testProducts;

    @BeforeAll
    void loadTestData() {
        repository = new ProductRepository(dataSource);
        testProducts = List.of(
            new Product("WIDGET-001", "Widget", Money.of(9.99)),
            new Product("GADGET-002", "Gadget", Money.of(24.99))
        );
        repository.saveAll(testProducts);
    }

    @Test
    void findByPriceRange_shouldReturnMatchingProducts() {
        List<Product> results = repository.findByPriceRange(
            Money.of(0), Money.of(15));
        assertThat(results).hasSize(1)
            .extracting(Product::sku)
            .containsExactly("WIDGET-001");
    }

    @Test
    void findBySku_shouldReturnCorrectProduct() {
        Optional<Product> product = repository.findBySku("GADGET-002");
        assertThat(product).isPresent()
            .map(Product::name)
            .hasValue("Gadget");
    }
}

Read-only tests can share a single loaded dataset. No need to reload for each test, and no rollback needed if tests don't mutate.

Configuring Default Lifecycle Globally

If your whole project uses integration tests with PER_CLASS, you can set the default in src/test/resources/junit-platform.properties:

junit.jupiter.testinstance.lifecycle.default=per_class

This removes the need for @TestInstance annotations on every class. Be careful: this changes behavior for all test classes in the project. Teams with a mix of unit and integration tests usually prefer explicit @TestInstance on integration test classes rather than a global default.

Common Mistakes

Using instance fields in @BeforeAll with PER_METHOD:

// WRONG - @BeforeAll is static, but field assignment to non-static field fails
@BeforeAll
static void setUp() {
    this.service = new Service(); // compile error
}

Either make service static or switch to PER_CLASS.

Expecting @AfterEach to run if @BeforeEach throws:

If @BeforeEach throws an exception, the test method is skipped but @AfterEach still runs. Plan your teardown to handle partial setup.

Assuming test execution order:

JUnit 5 randomizes test method order by default (in recent versions). Don't write tests where test2 depends on test1 having run first. Each test must be independently executable. If you need a specific order, use @TestMethodOrder(MethodOrderer.OrderAnnotation.class) and @Order — but treat this as a code smell, not a solution.

Summary

@BeforeEach/@AfterEach run around every test and are the right default for unit tests. @BeforeAll/@AfterAll run once per class and are for expensive resources that shouldn't be rebuilt per-test. Under PER_METHOD (the default), @BeforeAll must be static. Under PER_CLASS, it doesn't — and one test instance is reused throughout. In nested test hierarchies, outer setup wraps inner setup. Pick PER_METHOD for unit tests, PER_CLASS for integration tests with expensive startup, and be explicit about which you're using.

Read more

Start now free