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
@BeforeEachannotated method should be executed before each test. - The
@AfterEachannotated method should be executed after each test. - The
@BeforeAllannotated method should be executed before all tests. The annotated method should be static. - The
@AfterAllannotated 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.
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 {@BeforeAllpublic static void beforeAll() {System.out.println("Before all");}@BeforeEachpublic void beforeEach() {System.out.println("Before each");}@Testpublic void simpleTest1() {System.out.println("Test1");}@Testpublic void simpleTest2() {System.out.println("Test2");}@AfterEachpublic void afterEach() {System.out.println("After each");}@AfterAllpublic 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.