@Before (JUnit 4) or @BeforeEach (JUnit 5) runs before every individual test method, while @BeforeClass or @BeforeAll runs exactly once before any test methods in the class execute.
Key Points: • @Before/@BeforeEach is ideal for resetting per-test state, like creating a fresh object instance for isolation between tests. • @BeforeClass/@BeforeAll is ideal for expensive, shared setup, such as starting an embedded database or loading a large configuration file once. • @BeforeClass/@BeforeAll methods must be static in JUnit 4, and static by default in JUnit 5 unless the test class uses a per-class lifecycle. • Using @BeforeClass/@BeforeAll for per-test state can leak state between tests, causing order-dependent failures. • The corresponding teardown annotations, @After/@AfterEach and @AfterClass/@AfterAll, mirror this same per-test versus per-class distinction.
Example: A test class might use @BeforeEach to instantiate a fresh Calculator before every test, while using @BeforeAll to start a shared in-memory database connection once for the whole class.
Code Example:
@BeforeAll
static void startDatabase() {
embeddedDb.start();
}
@BeforeEach
void createCalculator() {
calculator = new Calculator();
}Interview Tip: A concise interview answer is:
"@Before or @BeforeEach runs before every single test method, which I use for per-test setup like creating fresh objects. @BeforeClass or @BeforeAll runs once before the whole class, which I reserve for expensive shared setup like starting an embedded database."