Lifecycle Annotations
Explore the use of JUnit 5 lifecycle annotations to control the execution order of tests. Understand how BeforeEach and AfterEach run around each test, and BeforeAll and AfterAll run once for all tests. This lesson helps you manage your test lifecycle for clearer and more efficient unit testing.
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.
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.