0
0
JUnittesting~15 mins

TestInstance lifecycle per class in JUnit - Build an Automation Script

Choose your learning style9 modes available
Verify that JUnit test instance lifecycle is per class
Preconditions (2)
Step 1: Create a test class annotated with @TestInstance(Lifecycle.PER_CLASS)
Step 2: Add a non-static field counter initialized to 0
Step 3: Add two test methods that increment the counter by 1
Step 4: Run the test class
Step 5: Observe the value of the counter after each test method
✅ Expected Result: The counter value should be 1 after the first test and 2 after the second test, showing the same test instance is used for both tests
Automation Requirements - JUnit 5
Assertions Needed:
Assert that the counter value is 1 in the first test method
Assert that the counter value is 2 in the second test method
Best Practices:
Use @TestInstance(Lifecycle.PER_CLASS) annotation on the test class
Use instance variables to track state across test methods
Use assertions from org.junit.jupiter.api.Assertions
Keep test methods independent except for the lifecycle behavior being tested
Automated Solution
JUnit
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import static org.junit.jupiter.api.Assertions.assertEquals;

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class TestInstancePerClassLifecycleTest {

    private int counter = 0;

    @Test
    void testIncrementCounterFirst() {
        counter++;
        assertEquals(1, counter, "Counter should be 1 after first test");
    }

    @Test
    void testIncrementCounterSecond() {
        counter++;
        assertEquals(2, counter, "Counter should be 2 after second test");
    }
}

The test class is annotated with @TestInstance(Lifecycle.PER_CLASS) to tell JUnit to use the same instance for all test methods.

The counter is an instance variable initialized to 0.

Each test method increments the counter by 1 and asserts the expected value.

Because the same instance is used, the counter value accumulates across tests, verifying the lifecycle behavior.

Common Mistakes - 3 Pitfalls
Not using @TestInstance(Lifecycle.PER_CLASS) annotation
Using static variables to track state instead of instance variables
Asserting wrong expected values due to misunderstanding lifecycle
Bonus Challenge

Now add a third test method that resets the counter to 0 and verify it resets correctly

Show Hint