0
0
JUnittesting~15 mins

@AfterAll method in JUnit - Build an Automation Script

Choose your learning style9 modes available
Verify @AfterAll method runs once after all tests
Preconditions (2)
Step 1: Create a test class with at least two test methods annotated with @Test
Step 2: Add a static method annotated with @AfterAll
Step 3: Inside the @AfterAll method, set a static boolean flag to true
Step 4: Run the test class
Step 5: Verify that the @AfterAll method was executed exactly once after all tests
✅ Expected Result: The @AfterAll method runs once after all test methods complete, and the static flag is set to true
Automation Requirements - JUnit 5
Assertions Needed:
Verify that the static flag is true after all tests run
Verify that the @AfterAll method is called exactly once
Best Practices:
Use static methods for @AfterAll
Use assertions inside test methods or after test execution to verify cleanup
Keep @AfterAll method simple and fast
Avoid side effects that affect other tests
Automated Solution
JUnit
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public class AfterAllExampleTest {
    private static boolean afterAllExecuted = false;

    @Test
    void testOne() {
        Assertions.assertFalse(afterAllExecuted, "@AfterAll should not run before tests");
    }

    @Test
    void testTwo() {
        Assertions.assertFalse(afterAllExecuted, "@AfterAll should not run before tests");
    }

    @AfterAll
    static void cleanup() {
        afterAllExecuted = true;
        System.out.println("@AfterAll method executed");
    }

    @Test
    void verifyAfterAllExecuted() {
        // This test runs before @AfterAll, so we cannot assert here
        // Instead, we rely on external verification or test runner output
    }
}

This test class has two test methods testOne and testTwo. Both assert that the afterAllExecuted flag is false, ensuring the @AfterAll method has not run yet.

The @AfterAll method cleanup is static as required by JUnit 5. It sets the flag to true and prints a message.

Since @AfterAll runs after all tests, the flag will be true only after all tests complete. We cannot assert the flag inside tests because they run before @AfterAll.

To verify the @AfterAll method ran, you can check the console output or use a test runner that supports lifecycle callbacks.

Common Mistakes - 3 Pitfalls
Making the @AfterAll method non-static
Trying to assert @AfterAll execution inside test methods
Putting heavy or slow code inside @AfterAll
Bonus Challenge

Now add a test class using @TestInstance(Lifecycle.PER_CLASS) to allow a non-static @AfterAll method

Show Hint