Explain the difference between @Before and @BeforeClass. How are they used?

@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

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.

@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.

Last updated: 16 July 2026

Previous question: What is JUnit, and why is it important for unit testing?

Next question: How do you test expected exceptions in JUnit?

More JUnit interview questions

All JUnit questions