In this post, we will talk and learn about the JUnit 5 life cycle @AfterAll annotation.
In JUnit 5 @AfterAll annotation is used to signal that the annotated method should be executed after all tests in the current test class.
It is a replacement for @AfterClass annotation in JUnit 4.
@AfterAll annotated method must be declared as a static method otherwise it will throw runtime error.
@AfterAll Annotation Example
Let’s understand @AfterAll Annotation using an example. Here I have MyUtils.java class with the add method. I will write a Junit test for this add method and we will see how we can make use of @AfterAll Annotation in the same Unit class
Utility Class for that we have to write JUnit Test:
1 2 3 4 5 6 7 8 |
package kkjavatutorials.com; public class MyUtils { public int add (int n1,int n2) { return n1+n2; } } |
JUnit Test Class, method setUp() is annotated with @BeforeAll and method tearDown() is annotated with @AfterAll Annotation.
NOTE: Both setUp() and tearDown() method must be declared as static else it will throw Runtime Exception.
1 2 3 4 5 6 |
org.junit.platform.commons.JUnitException: @AfterAll method 'void kkjavatutorials.com.MyUtilsTest.tearDown()' must be static unless the test class is annotated with @TestInstance(Lifecycle.PER_CLASS). at org.junit.jupiter.engine.descriptor.LifecycleMethodUtils.assertStatic(LifecycleMethodUtils.java:57) at org.junit.jupiter.engine.descriptor.LifecycleMethodUtils.lambda$findMethodsAndAssertStatic$0(LifecycleMethodUtils.java:81) at java.util.ArrayList.forEach(ArrayList.java:1249) at java.util.Collections$UnmodifiableCollection.forEach(Collections.java:1080) at org.junit.jupiter.engine.descriptor.LifecycleMethodUtils.findMethodsAndAssertStatic(LifecycleMethodUtils.java:81) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
package kkjavatutorials.com; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; class MyUtilsTest { private static MyUtils myUtils; @BeforeAll static void setUp(){ System.out.println("Test data set up.."); myUtils = new MyUtils(); } @Test void addTest() { System.out.println("addTest Method.."); assertEquals(10, myUtils.add(6, 4)); } @AfterAll static void tearDown(){ System.out.println("Test data tearDown.."); myUtils = null; } } |
The output of the above test class
You may also Like:
Junit 5 Architecture
JUnit 5 Annotations
JUnit 5 Maven Dependency
JUnit 5 Test Lifecycle
That’s all about JUnit 5 @AfterAll annotation example
If you have any feedback or suggestion please feel free to drop in below comment box.