How to Use @AfterEach in JUnit for Test Cleanup
In JUnit, use the
@AfterEach annotation to mark a method that runs after each test method completes. This is useful for cleaning up resources or resetting states to keep tests independent and reliable.Syntax
The @AfterEach annotation is placed above a method that you want to run after every test method in the class. This method must be void and take no parameters.
Example parts:
@AfterEach: Marks the method to run after each test.void cleanup(): The method name can be anything but should describe the cleanup task.
java
import org.junit.jupiter.api.AfterEach; public class TestClass { @AfterEach void cleanup() { // code to run after each test } }
Example
This example shows a test class where a list is cleared after each test to ensure tests do not affect each other.
java
import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; public class ListTest { private List<String> list = new ArrayList<>(); @Test void testAdd() { list.add("apple"); assertEquals(1, list.size()); } @Test void testEmpty() { assertEquals(0, list.size()); } @AfterEach void cleanup() { list.clear(); } }
Output
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
Common Pitfalls
Common mistakes when using @AfterEach include:
- Not clearing or resetting shared resources, causing tests to interfere with each other.
- Using
@AfterEachon methods with parameters or non-void return types, which will cause errors. - Confusing
@AfterEachwith@AfterAll, which runs once after all tests.
java
import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; public class WrongAfterEach { // Wrong: method has a parameter @AfterEach void cleanup(String param) { // This will cause a compile-time error } // Correct: @AfterEach void cleanup() { // Proper cleanup code } @Test void testSomething() { // test code } }
Quick Reference
| Annotation | Purpose | Method Requirements |
|---|---|---|
| @AfterEach | Runs after each test method | void return type, no parameters |
| @BeforeEach | Runs before each test method | void return type, no parameters |
| @AfterAll | Runs once after all tests | static void return type, no parameters |
| @BeforeAll | Runs once before all tests | static void return type, no parameters |
Key Takeaways
Use @AfterEach to run cleanup code after every test method to keep tests independent.
The method annotated with @AfterEach must be void and take no parameters.
Common errors include using parameters in @AfterEach methods or confusing it with @AfterAll.
@AfterEach helps prevent side effects between tests by resetting shared resources.
Remember to pair @AfterEach with @BeforeEach for balanced setup and teardown.