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.