0
0
JUnittesting~5 mins

@AfterEach method in JUnit

Choose your learning style9 modes available
Introduction

The @AfterEach method runs after every test to clean up or reset things. It helps keep tests independent and tidy.

You want to close a database connection after each test.
You need to reset shared variables or states after every test.
You want to delete temporary files created during a test.
You want to clear mock objects or reset configurations after each test.
Syntax
JUnit
@AfterEach
void methodName() {
    // cleanup code here
}

The method must be void and take no parameters.

It runs after each test method in the class.

Examples
This prints a message after each test runs.
JUnit
@AfterEach
void cleanup() {
    System.out.println("Cleaning up after test");
}
This resets a counter variable after every test.
JUnit
@AfterEach
void resetCounter() {
    counter = 0;
}
Sample Program

This test class has two tests. Each test starts with total set to 5. After each test, total is reset to 0 by the @AfterEach method. The print statements show the order of execution.

JUnit
import org.junit.jupiter.api.*;

class CalculatorTest {
    int total = 0;

    @BeforeEach
    void setup() {
        total = 5;
        System.out.println("Setup total to " + total);
    }

    @Test
    void testAdd() {
        total += 3;
        Assertions.assertEquals(8, total);
        System.out.println("Test add total: " + total);
    }

    @Test
    void testSubtract() {
        total -= 2;
        Assertions.assertEquals(3, total);
        System.out.println("Test subtract total: " + total);
    }

    @AfterEach
    void cleanup() {
        total = 0;
        System.out.println("Cleanup total to " + total);
    }
}
OutputSuccess
Important Notes

Use @AfterEach to avoid tests affecting each other.

If you want code to run once after all tests, use @AfterAll instead.

Summary

@AfterEach runs after every test method.

It helps clean up or reset things to keep tests independent.

Methods annotated with @AfterEach must be void and no-argument.