How would you use the JUnit @Before, @After and @BeforeAll annotations in a practical test case?

JUnit lifecycle annotations control setup and teardown around tests, letting you prepare shared resources once and reset per-test state cleanly between runs.

Key Points

Example

A repository test class opens a Testcontainers PostgreSQL instance once in @BeforeAll, inserts fresh seed data in @BeforeEach for each test, and truncates the tables in @AfterEach so every test starts from a known state.

class UserRepositoryTest {

    @BeforeAll
    static void startDb() { /* start container */ }

    @BeforeEach
    void seedData() { /* insert test rows */ }

    @AfterEach
    void cleanUp() { /* truncate tables */ }

    @AfterAll
    static void stopDb() { /* stop container */ }
}

Interview Tip

A concise interview answer is

I use @BeforeAll for one-time expensive setup like starting a test database, @BeforeEach to prepare fresh data before each individual test, and @AfterEach or @AfterAll to clean up so no state leaks between tests. That keeps every test independent and repeatable regardless of run order.

Last updated: 11 November 2026

Previous question: What do the JUnit annotations @Before, @After and @BeforeAll do?

Next question: What are the HTTP methods used in REST APIs?

More Spring Boot - Level IV (Advanced) interview questions

All Spring Boot - Level IV (Advanced) questions