JUnit lifecycle annotations control setup and teardown around tests, letting you prepare shared resources once and reset per-test state cleanly between runs.
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 */ }
}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?