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 |