0
0
JUnittesting~5 mins

@AfterAll method in JUnit

Choose your learning style9 modes available
Introduction

The @AfterAll method runs once after all tests finish. It helps clean up resources or reset settings.

Close a database connection after all tests complete.
Delete temporary files created during tests.
Stop a server or service started for testing.
Reset shared test data or configurations.
Log summary information after all tests run.
Syntax
JUnit
@AfterAll
static void methodName() {
    // cleanup code here
}

The method must be static in JUnit 5.

It runs only once after all test methods in the class.

Examples
This prints a message after all tests finish.
JUnit
@AfterAll
static void tearDown() {
    System.out.println("All tests done.");
}
This closes a database connection after all tests.
JUnit
@AfterAll
static void closeConnection() {
    database.close();
}
Sample Program

This class has two tests. After both run, the @AfterAll method prints a final message.

JUnit
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Test;

public class SampleTest {

    @Test
    void testOne() {
        System.out.println("Test one running");
    }

    @Test
    void testTwo() {
        System.out.println("Test two running");
    }

    @AfterAll
    static void afterAllTests() {
        System.out.println("All tests completed");
    }
}
OutputSuccess
Important Notes

If the @AfterAll method is not static, tests will fail to run.

Use @AfterAll for actions that should happen once, not after each test.

Summary

@AfterAll runs once after all tests in a class.

The method must be static in JUnit 5.

Use it to clean up shared resources or do final steps.