Test Overview
This test demonstrates the use of the @AfterEach method in JUnit. It verifies that a resource is properly reset after each test method runs.
This test demonstrates the use of the @AfterEach method in JUnit. It verifies that a resource is properly reset after each test method runs.
import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; public class CounterTest { private Counter counter = new Counter(); @BeforeEach void setUp() { } @AfterEach void reset() { counter.reset(); } @Test void testIncrement() { counter.increment(); assertEquals(1, counter.getValue()); } @Test void testDecrement() { counter.decrement(); assertEquals(-1, counter.getValue()); } } class Counter { private int value = 0; void increment() { value++; } void decrement() { value--; } int getValue() { return value; } void reset() { value = 0; } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test framework initializes and calls setUp() before testIncrement() | Counter value is 0 (initial state) | — | PASS |
| 2 | testIncrement() calls counter.increment() | Counter value increases from 0 to 1 | assertEquals(1, counter.getValue()) verifies value is 1 | PASS |
| 3 | After testIncrement(), reset() is called by @AfterEach | Counter value resets from 1 to 0 | — | PASS |
| 4 | Test framework initializes and calls setUp() before testDecrement() | Counter value is 0 (from previous reset) | — | PASS |
| 5 | testDecrement() calls counter.decrement() | Counter value decreases from 0 to -1 | assertEquals(-1, counter.getValue()) verifies value is -1 | PASS |
| 6 | After testDecrement(), reset() is called by @AfterEach | Counter value resets from -1 to 0 | — | PASS |
@AfterEach in JUnit?@AfterEach annotation marks methods that run after every test method to clean up or reset state.@AfterEach in JUnit?@AfterEach must be void, no-argument, and instance methods (not static).class ExampleTest {
int count = 0;
@AfterEach
void reset() {
count = 0;
}
@Test
void testIncrement() {
count++;
assertEquals(1, count);
}
@Test
void testDecrement() {
count--;
assertEquals(-1, count);
}
}reset() method sets count to 0 after each test method runs, so each test starts fresh.testIncrement(), count increments from 0 to 1, assertion matches. In testDecrement(), count decrements from 0 to -1, assertion matches. Both pass.class SampleTest {
@AfterEach
public static void cleanup() {
System.out.println("Cleaning up");
}
@Test
void testSomething() {
assertTrue(true);
}
}cleanup() is declared static, which violates the rule.@AfterEach?@AfterEach to close the connection ensures it happens after every test, keeping tests independent and safe.Pass the test and this pattern moves unknown