JUnit 5 Lifecycle - @BeforeAll, @BeforeEach, @AfterAll, @AfterEach
@BeforeAll
A method annotated with @BeforeAll is executed exactly once before all test methods in the test class. It is used for heavy setup that should happen once per class, such as opening a database connection or starting an embedded server. The method signature must be static.
@BeforeAll
static void runOnceBeforeAllTests() {
System.out.println("@BeforeAll executed \n");
}
@BeforeEach
A method annotated with @BeforeEach is executed before each test method.
@BeforeEach
void runBeforeEveryTest() {
System.out.println("@BeforeEach executed");
}
@AfterEach
A method annotated with @AfterEach is executed after each test method.
@AfterEach
void runAfterEveryTest() {
System.out.println("@AfterEach executed \n");
}
@AfterAll
A method annotated with @AfterAll is executed exactly once after all test methods in the test class. It is usually used to close resources opened in @BeforeAll, such as database connections or embedded servers. The method signature must be static.
@AfterAll
static void runOnceAfterAllTests() {
System.out.println("@AfterAll executed");
}
Execution Order
The lifecycle order is @BeforeAll, then for each test @BeforeEach, @Test, @AfterEach, and finally @AfterAll.