0
0
JUnittesting~15 mins

@AfterEach method in JUnit - Build an Automation Script

Choose your learning style9 modes available
Verify resource cleanup after each test using @AfterEach
Preconditions (2)
Step 1: Create a test class with two test methods that open a resource (e.g., a list)
Step 2: In each test method, add an item to the resource
Step 3: Add an @AfterEach method that clears the resource after each test
Step 4: Run the tests
✅ Expected Result: After each test method runs, the resource is cleared so that the next test starts with an empty resource
Automation Requirements - JUnit 5
Assertions Needed:
Verify the resource is empty at the start of each test
Verify the resource contains the expected item after adding
Verify the resource is cleared after each test via @AfterEach
Best Practices:
Use @BeforeEach to initialize resources if needed
Use @AfterEach to clean up resources to avoid test interference
Use assertions from org.junit.jupiter.api.Assertions
Keep test methods independent
Automated Solution
JUnit
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.

Common Mistakes - 3 Pitfalls
Not clearing or resetting shared resources after each test
Using @AfterAll instead of @AfterEach for cleanup
Modifying resources in @AfterEach without proper initialization in @BeforeEach
Bonus Challenge

Now add a third test method that adds two items and verify the resource is still cleared after the test

Show Hint