0
0
JUnittesting~10 mins

@AfterEach method in JUnit - Test Execution Trace

Choose your learning style9 modes available
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.

Test Code - JUnit 5
JUnit
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;
    }
}
Execution Trace - 6 Steps
StepActionSystem StateAssertionResult
1Test framework initializes and calls setUp() before testIncrement()Counter value is 0 (initial state)-PASS
2testIncrement() calls counter.increment()Counter value increases from 0 to 1assertEquals(1, counter.getValue()) verifies value is 1PASS
3After testIncrement(), reset() is called by @AfterEachCounter value resets from 1 to 0-PASS
4Test framework initializes and calls setUp() before testDecrement()Counter value is 0 (from previous reset)-PASS
5testDecrement() calls counter.decrement()Counter value decreases from 0 to -1assertEquals(-1, counter.getValue()) verifies value is -1PASS
6After testDecrement(), reset() is called by @AfterEachCounter value resets from -1 to 0-PASS
Failure Scenario
Failing Condition: If the reset() method is missing or does not reset the counter value, the counter state will carry over between tests.
Execution Trace Quiz - 3 Questions
Test your understanding
What is the purpose of the @AfterEach method in this test?
ATo run the test methods in order
BTo initialize the counter before each test
CTo reset the counter after each test method runs
DTo assert the counter value
Key Result
Using @AfterEach ensures that any changes made during a test are cleaned up, keeping tests independent and reliable.