0
0
JUnittesting~10 mins

@AfterAll method in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test demonstrates the use of the @AfterAll method in JUnit. It verifies that a cleanup method runs once after all tests complete.

Test Code - JUnit
JUnit
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

public class AfterAllExampleTest {

    private static int resource;

    @BeforeAll
    public static void setup() {
        resource = 5;
        System.out.println("Setup done");
    }

    @Test
    public void testAddition() {
        int result = resource + 10;
        Assertions.assertEquals(15, result);
    }

    @Test
    public void testMultiplication() {
        int result = resource * 2;
        Assertions.assertEquals(10, result);
    }

    @AfterAll
    public static void cleanup() {
        resource = 0;
        System.out.println("Cleanup done");
    }
}
Execution Trace - 4 Steps
StepActionSystem StateAssertionResult
1JUnit starts test run and calls @BeforeAll methodStatic variable 'resource' is set to 5-PASS
2JUnit runs testAddition methodresource = 5Check if resource + 10 equals 15PASS
3JUnit runs testMultiplication methodresource = 5Check if resource * 2 equals 10PASS
4JUnit calls @AfterAll method after all testsresource is reset to 0-PASS
Failure Scenario
Failing Condition: @AfterAll method is missing or throws exception
Execution Trace Quiz - 3 Questions
Test your understanding
When is the @AfterAll method executed in a JUnit test class?
AAfter all test methods have run
BBefore each test method
CBefore all test methods
DAfter each test method
Key Result
Use @AfterAll to run cleanup code once after all tests finish. The method must be static and public to work correctly.