0
0
JUnittesting~10 mins

Test independence in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test checks that two JUnit test methods run independently without sharing state. It verifies that the counter variable resets for each test method, ensuring test independence.

Test Code - JUnit 5
JUnit
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

public class CounterTest {
    private int counter;

    @BeforeEach
    void setUp() {
        counter = 0;
    }

    @Test
    void testIncrementOnce() {
        counter++;
        assertEquals(1, counter);
    }

    @Test
    void testIncrementTwice() {
        counter++;
        counter++;
        assertEquals(2, counter);
    }
}
Execution Trace - 4 Steps
StepActionSystem StateAssertionResult
1JUnit framework initializes test class instance and calls @BeforeEach methodcounter variable is set to 0-PASS
2testIncrementOnce method runs and increments counter by 1counter value is 1assertEquals(1, counter) verifies counter is 1PASS
3JUnit framework initializes new test class instance and calls @BeforeEach method againcounter variable is reset to 0-PASS
4testIncrementTwice method runs and increments counter by 2counter value is 2assertEquals(2, counter) verifies counter is 2PASS
Failure Scenario
Failing Condition: If the counter variable is shared between tests and not reset, the second test will fail because counter will not start at 0.
Execution Trace Quiz - 3 Questions
Test your understanding
Why does the counter variable reset to 0 before each test method?
ABecause the tests run in parallel
BBecause the @BeforeEach method runs before every test to reset state
CBecause the counter variable is static and shared
DBecause the counter is initialized only once
Key Result
Always reset shared state before each test method using setup methods like @BeforeEach to ensure tests run independently and do not affect each other.