0
0
JUnittesting~10 mins

TestInstance lifecycle per class in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test demonstrates how JUnit creates a single test instance for all test methods when using @TestInstance(Lifecycle.PER_CLASS). It verifies that the same object is used across tests by incrementing a counter.

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

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class CounterTest {
    private int counter = 0;

    @BeforeAll
    void setup() {
        counter = 1;
    }

    @Test
    void testIncrement1() {
        counter++;
        assertTrue(counter > 1, "Counter should be greater than 1");
    }

    @Test
    void testIncrement2() {
        counter++;
        assertTrue(counter > 2, "Counter should be greater than 2");
    }
}
Execution Trace - 4 Steps
StepActionSystem StateAssertionResult
1JUnit creates a single test instance of CounterTest for all tests due to @TestInstance(PER_CLASS)CounterTest instance created with counter = 0-PASS
2@BeforeAll method setup() runs and sets counter = 1CounterTest instance counter is now 1-PASS
3testIncrement1() runs, increments counter to 2CounterTest instance counter is 2assertTrue(counter > 1) verifies counter is 2PASS
4testIncrement2() runs, increments counter to 3CounterTest instance counter is 3assertTrue(counter > 2) verifies counter is 3PASS
Failure Scenario
Failing Condition: If @TestInstance(Lifecycle.PER_CLASS) is missing, JUnit defaults to PER_METHOD lifecycle, requiring @BeforeAll methods to be static, but setup() is non-static.
Execution Trace Quiz - 3 Questions
Test your understanding
What does @TestInstance(Lifecycle.PER_CLASS) do in this test?
ARuns tests in parallel threads
BCreates a new test instance for each test method
CCreates one test instance shared by all test methods
DDisables the test methods
Key Result
Using @TestInstance(Lifecycle.PER_CLASS) allows sharing state between test methods by using a single test class instance, which is useful for tests that depend on shared mutable state.