Verify resource cleanup after each test using @AfterEach
Preconditions (2)
✅ Expected Result: After each test method runs, the resource is cleared so that the next test starts with an empty resource
import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import static org.junit.jupiter.api.Assertions.*; public class ResourceCleanupTest { private List<String> resource; @BeforeEach void setUp() { resource = new ArrayList<>(); assertTrue(resource.isEmpty(), "Resource should be empty before each test"); } @Test void testAddItemOne() { resource.add("item1"); assertEquals(1, resource.size(), "Resource should contain one item"); assertTrue(resource.contains("item1"), "Resource should contain 'item1'"); } @Test void testAddItemTwo() { resource.add("item2"); assertEquals(1, resource.size(), "Resource should contain one item"); assertTrue(resource.contains("item2"), "Resource should contain 'item2'"); } @AfterEach void tearDown() { resource.clear(); assertTrue(resource.isEmpty(), "Resource should be empty after each test"); } }
This test class demonstrates the use of @AfterEach in JUnit 5 to clean up resources after each test method.
setUp() method annotated with @BeforeEach initializes the resource and asserts it is empty before each test.
Two test methods add different items to the resource and verify the additions.
The @AfterEach method tearDown() clears the resource and asserts it is empty after each test, ensuring no leftover data affects other tests.
This pattern keeps tests independent and avoids side effects.
Now add a third test method that adds two items and verify the resource is still cleared after the test
@AfterEach in JUnit?@AfterEach annotation marks methods that run after every test method to clean up or reset state.@AfterEach in JUnit?@AfterEach must be void, no-argument, and instance methods (not static).class ExampleTest {
int count = 0;
@AfterEach
void reset() {
count = 0;
}
@Test
void testIncrement() {
count++;
assertEquals(1, count);
}
@Test
void testDecrement() {
count--;
assertEquals(-1, count);
}
}reset() method sets count to 0 after each test method runs, so each test starts fresh.testIncrement(), count increments from 0 to 1, assertion matches. In testDecrement(), count decrements from 0 to -1, assertion matches. Both pass.class SampleTest {
@AfterEach
public static void cleanup() {
System.out.println("Cleaning up");
}
@Test
void testSomething() {
assertTrue(true);
}
}cleanup() is declared static, which violates the rule.@AfterEach?@AfterEach to close the connection ensures it happens after every test, keeping tests independent and safe.Pass the test and this pattern moves unknown