Lifecycle Annotations

Learn the lifecycle methods annotated with the @BeforeAll, @AfterAll, @BeforeEach, and @AfterEach annotations.

We'll cover the following

JUnit 5 annotations

JUnit 5 has four annotations related to the test lifecycle:

  • The @BeforeEach annotated method should be executed before each test.
  • The @AfterEach annotated method should be executed after each test.
  • The @BeforeAll annotated method should be executed before all tests. The annotated method should be static.
  • The @AfterAll annotated method should be executed after all tests. The annotated method should be static.

The code below shows the usage of these annotations.

We have two tests, simpleTest1() and simpleTest2(), that test all annotations sequentially and give the result pass or fail.

Methods annotated with @BeforeEach and @AfterEach, as the name suggests, are called before and after each @Test method. Similarly, @BeforeAll and @AfterAll are called before and after all @Test methods. Let’s look at a demo taking the previous test class.

Press + to interact
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.BeforeAll;
public class AnnotationTest {
@BeforeAll
public static void beforeAll() {
System.out.println("Before all");
}
@BeforeEach
public void beforeEach() {
System.out.println("Before each");
}
@Test
public void simpleTest1() {
System.out.println("Test1");
}
@Test
public void simpleTest2() {
System.out.println("Test2");
}
@AfterEach
public void afterEach() {
System.out.println("After each");
}
@AfterAll
public static void afterAll() {
System.out.println("After all");
}
}

The sample output looks like this:

In the output above, the @BeforeAll method first executes before all test cases. After that, the @BeforeEach method executes, before each test case. The Test1 then executes, and the @AfterEach method executes after each test case.

In the output above, the @BeforeEach method first executes before each test case. The Test2 then executes, and the @AfterEach method then executes after each test case.

In the end, the @AfterAll method executes because all test cases have been executed.