JUnit 5 lifecycle
The JUnit 5 lifecycle is the fixed order in which JUnit creates your test class and runs its setup, test, and teardown methods. By default JUnit builds a fresh instance of the class for every single test method.
Detailed Explanation
A test usually needs some setup. You want an empty cart, a clean temporary folder, or a stub clock fixed to a known date. Writing that setup inside every test method is repetitive, so JUnit gives you hook annotations and guarantees when it calls them.
There are five hooks, and the order is fixed:
| Annotation | Runs | Must be static? |
|---|---|---|
@BeforeAll | once, before any test in the class | yes, by default |
@BeforeEach | before every test method | no |
@Test | the test itself | no |
@AfterEach | after every test method, even a failing one | no |
@AfterAll | once, after the last test in the class | yes, by default |
The static requirement on @BeforeAll catches everyone once. JUnit has not created an instance of your class at that point, so there is no object for a non-static method to run on.
The reason for the requirement is the part worth understanding: JUnit creates a new instance of the test class for every test method. This is the per-method test instance lifecycle. If testA assigns a field, testB sees the field back at its default value, because testB runs against a different object. Fresh state per test is what makes tests independent, which is what lets you run them in any order, in parallel, or one at a time from the IDE while debugging.
The exception is @TestInstance(TestInstance.Lifecycle.PER_CLASS) on the class. Then JUnit reuses one instance for all tests, @BeforeAll and @AfterAll no longer need to be static, and @MethodSource factory methods can be instance methods too. The trade is real: shared state comes back, and one test can now corrupt the next. Use it when construction is genuinely expensive, not for convenience.
JUnit 4 called these hooks @Before and @After and created a new instance per test as well, but the modern names say what they do. JUnit 4's @BeforeClass is JUnit 5's @BeforeAll.
Everything else hangs off extensions. @ExtendWith(SomeExtension.class) plugs third-party code into the same lifecycle, which is how MockitoExtension resets mocks between tests and how SpringExtension boots an application context once and shares it across classes. Writing your own extension means implementing an interface such as BeforeEachCallback. This replaced JUnit 4's rules and runners, and unlike runners you can stack as many extensions as you like.
The cost of heavy setup is paid per test, not per class. A @BeforeEach that opens a database connection multiplies by the number of test methods. Put slow one-time work in @BeforeAll, keep @BeforeEach to cheap object construction, and always release resources in @AfterEach so a failing test does not leak into the rest of the suite.
Code Examples
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
class LifecycleOrderTest {
// Instance field: recreated for every test method.
private final List<String> visited = new ArrayList<>();
@BeforeAll
static void openSharedResource() {
// static because no instance of this class exists yet
System.out.println("beforeAll");
}
@BeforeEach
void showFreshState() {
// Prints 0 both times, because each test gets a brand new instance.
System.out.println("beforeEach, visited = " + visited.size());
}
@Test
void firstTest() {
visited.add("first");
}
@Test
void secondTest() {
visited.add("second");
}
@AfterEach
void showEndState() {
System.out.println("afterEach, visited = " + visited.size());
}
@AfterAll
static void closeSharedResource() {
System.out.println("afterAll");
}
}
// prints: beforeAll
// prints: beforeEach, visited = 0
// prints: afterEach, visited = 1
// prints: beforeEach, visited = 0
// prints: afterEach, visited = 1
// prints: afterAllimport org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import static org.junit.jupiter.api.Assertions.assertTrue;
// One instance shared by every test in this class.
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class SharedInstanceTest {
private String expensiveFixture;
@BeforeAll
void buildFixture() { // no "static" needed under PER_CLASS
expensiveFixture = "loaded once";
}
@Test
void fixtureIsAvailable() {
assertTrue(expensiveFixture.startsWith("loaded"));
}
}Common Gotchas
Non-static `@BeforeAll` fails at runtime
with the default per-method lifecycle, a non-static `@BeforeAll` method throws `JUnitException` before any test runs. Either make it `static` or switch the class to `PER_CLASS`.
`@AfterEach` is your only cleanup guarantee
cleanup written at the end of a test method never runs when an assertion fails earlier in that method. Temporary files and open connections leak into the next test. Put teardown in `@AfterEach`, or use `@TempDir` and let JUnit handle it.
`@BeforeEach` runs after the constructor
JUnit builds the object first, then injects parameters, then calls `@BeforeEach`. Field initialisers and constructor code therefore run before any hook, which is why a `final` field initialised inline is still fresh for every test.