In JUnit testing, what are the annotations @Before, @After, @BeforeAll?

@Before, @After, and @BeforeAll (or their JUnit 5 equivalents @BeforeEach, @AfterEach, and @BeforeAll) are lifecycle annotations that control setup and teardown code around test method execution in a JUnit test class.

Key Points: • @Before (JUnit 4) / @BeforeEach (JUnit 5) runs before every test method, ideal for resetting shared state. • @After (JUnit 4) / @AfterEach (JUnit 5) runs after every test method, typically for cleanup like closing resources. • @BeforeAll runs once before any test method in the class executes, suited to expensive one-time setup like opening a database connection. • @AfterAll is the once-only counterpart that runs after all tests complete, releasing shared resources. • In JUnit 5, methods annotated @BeforeAll and @AfterAll must be static unless the test class uses per-class lifecycle mode.

Example: A repository test class uses @BeforeAll to start an embedded database once for the whole class, and @BeforeEach to insert a fresh set of test rows before every individual test method runs.

Code Example:

@BeforeAll
static void initDb() {
    embeddedDb.start();
}

@BeforeEach
void seedData() {
    repository.save(new User("test"));
}

@AfterEach
void clearData() {
    repository.deleteAll();
}

Interview Tip: A concise interview answer is:

"@Before or @BeforeEach runs before each test for per-test setup, @After or @AfterEach runs after each test for cleanup, and @BeforeAll runs once before the entire class for expensive setup like establishing a database connection. Getting this right keeps tests isolated without repeating costly setup unnecessarily."