Skip to content
javahacks.dev
JUnit

JUnit Test Instance Lifecycle and Shared State Explained

How JUnit creates a new test instance per method by default, when PER_CLASS changes it and what that means for shared state and parallel runs.

8 min read
Summarize in AI
Flat illustration of a JUnit test run with one failing test, with the JUnit5, OpenJDK, Cucumber and Jenkins logos.

Two tests in one class, each incrementing a counter field, and both pass. Most developers never stop to ask why, and the answer shapes how every JUnit test suite behaves: JUnit does not reuse the test class object. It builds a new one for each test method, so the second test sees a counter that is zero again. This post explains the lifecycle mechanics, the one annotation that changes them, what each choice means for shared state and parallel execution and the rules that keep tests independent. The annotations that run before and after tests are covered in JUnit lifecycle annotations and execution order; this post is about the objects those methods run on. Examples use JUnit Jupiter, whose programming model is the same in JUnit 5 and JUnit 6.

The default: a new instance per test

Run this class and look at the output:

src/test/java/dev/javahacks/lifecycle/PerMethodTest.javajava
package dev.javahacks.lifecycle;

import org.junit.jupiter.api.*;

class PerMethodTest {

    private int counter = 0;

    PerMethodTest() {
        System.out.println("new instance " + System.identityHashCode(this));
    }

    @Test
    void first() {
        counter++;
        System.out.println("first: counter=" + counter + " on " + System.identityHashCode(this));
        Assertions.assertEquals(1, counter);
    }

    @Test
    void second() {
        counter++;
        System.out.println("second: counter=" + counter + " on " + System.identityHashCode(this));
        Assertions.assertEquals(1, counter);       // passes: the counter started at zero again
    }
}
Text
new instance 1163157884
first: counter=1 on 1163157884
new instance 1956725890
second: counter=1 on 1956725890

Two different instances, two different identity hash codes. The constructor ran twice, once per test, and each test method ran on its own object. This is called the PER_METHOD lifecycle, and it is the default in JUnit Jupiter and was the only behaviour in JUnit 4. Its value is isolation by construction: no test can corrupt the state another test sees, because they never share an object. A field assignment in one test is invisible to the next, and tests can be run in any order, or in parallel, without that mattering for instance fields.

The sequence for one test under this lifecycle is:

  1. Construct a new instance of the test class.
  2. Run every @BeforeEach method on it.
  3. Run the test method.
  4. Run every @AfterEach method.
  5. Discard the instance.

@BeforeAll and @AfterAll wrap the whole class, and since no instance exists when they run, they must be static under this lifecycle. A non static @BeforeAll produces an error that explains it:

Text
org.junit.platform.commons.JUnitException: @BeforeAll method 'void dev.javahacks.lifecycle.PerMethodTest.setUp()'
must be static unless the test class is annotated with @TestInstance(Lifecycle.PER_CLASS).

Opting into one instance: PER_CLASS

The annotation @TestInstance(Lifecycle.PER_CLASS) tells JUnit to create the instance once and run every test on it:

src/test/java/dev/javahacks/lifecycle/PerClassTest.javajava
package dev.javahacks.lifecycle;

import org.junit.jupiter.api.*;

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class PerClassTest {

    private int counter = 0;

    PerClassTest() {
        System.out.println("new instance " + System.identityHashCode(this));
    }

    @BeforeAll
    void startUp() {                              // not static: allowed with PER_CLASS
        System.out.println("beforeAll on " + System.identityHashCode(this));
    }

    @Test
    @Order(1)
    void first() {
        counter++;
        System.out.println("first: counter=" + counter);
    }

    @Test
    @Order(2)
    void second() {
        counter++;
        System.out.println("second: counter=" + counter);     // 2, the state leaked from the first test
    }
}
Text
new instance 482932940
beforeAll on 482932940
first: counter=1
second: counter=2

One instance, one constructor call, and the field kept its value. That changes three things.

**@BeforeAll and @AfterAll can be ordinary instance methods.** Setup can then use instance fields and the instance's own helper methods, which is the main reason people choose this lifecycle, especially in Kotlin where static needs a companion object.

Instance state is shared. Every field is now like a static one, scoped to the class. A test that modifies a list or a counter changes what the next test sees. If the tests happen to run in the declared order the suite passes; run one alone, or in another order, or in parallel, and it fails.

**@Nested classes get more convenient.** An inner test class inherits the outer instance's context. With PER_CLASS on the outer class, an expensive setup in the outer @BeforeAll is shared by the nested tests instead of repeating, which is an honest reason to use it for structured tests.

What the lifecycle means for shared state

The two lifecycles are two answers to "where does state live". Match the state to the right place:

StateWhere it belongsWhy
A fresh object under test, a mock, a builderAn instance field, initialised in @BeforeEach or the field initialiserEach test needs its own, so use PER_METHOD
An expensive read only fixture, a parsed schema, a compiled regexA static final field or @BeforeAllCreate once, never mutate
A started container or an embedded server@BeforeAll, or better an extensionSeconds to start; share across tests
A database with dataA transaction rolled back per test, or reset in @BeforeEachThe data is shared infrastructure; the test must clean up after itself
A counter used to assert somethingA local variable inside the testState that matters to one test should not outlive it

The common bug is a mutable object promoted from per test to per class for speed, and now two tests interfere. A test that fails only when run after another is the signature. Rather than fix such a bug with @Order, fix the sharing, which is the cause.

A shared mutable list, step by step

The failure is easy to reproduce, and seeing it once makes the rule memorable. A static list shared across tests behaves like PER_CLASS state:

src/test/java/dev/javahacks/lifecycle/SharedListTest.javajava
class SharedListTest {

    private static final List<String> events = new ArrayList<>();      // shared by every instance

    @Test
    void recordsOne() {
        events.add("one");
        Assertions.assertEquals(1, events.size());
    }

    @Test
    void recordsTwo() {
        events.add("two");
        Assertions.assertEquals(1, events.size());      // passes or fails depending on which ran first
    }
}

Run the class and, depending on method order (JUnit's default order is deterministic but not obvious), one of the two fails with expected: <1> but was: <2>. The fix is to make the list a per instance field, so PER_METHOD gives each test its own:

java
private final List<String> events = new ArrayList<>();      // new for every test under PER_METHOD

The one line change turns a lifecycle dependent bug into isolation by construction.

Parallel execution

JUnit can run test classes and methods in parallel, enabled in junit-platform.properties:

src/test/resources/junit-platform.propertiesproperties
junit.jupiter.execution.parallel.enabled=true
junit.jupiter.execution.parallel.mode.default=concurrent

The lifecycle decides how safe that is. Under PER_METHOD, instance fields are not shared, so methods in the same class can run at once without interfering through fields. Under PER_CLASS, concurrent methods run on the same object, so every shared field is a data race. Static fields and external resources, such as a database table or a file, are shared in both lifecycles. When you turn on parallelism, audit three things: static mutable state, shared files and ports, and global resources like System.setProperty. Mark tests that cannot run concurrently with @Execution(ExecutionMode.SAME_THREAD) or guard the resource with @ResourceLock("database"). More on this is in running JUnit tests in parallel.

Changing the default for a project

If a team standardises on PER_CLASS, for instance for Kotlin, set it once instead of annotating every class:

src/test/resources/junit-platform.propertiesproperties
junit.jupiter.testinstance.lifecycle.default=per_class

Be deliberate about it. A project default of per_class removes the isolation guarantee from every test in the codebase, and every developer must now keep instance state clean by discipline. Most projects are better served by the default and a targeted annotation on the few classes that need it.

Spring tests and the lifecycle

In Spring Boot tests the test class instance is distinct from the application context. The context is cached and shared across test classes with the same configuration, no matter the instance lifecycle, which is the main reason Spring suites are fast; see Spring test context caching. Injected fields such as @Autowired MockMvc mvc are set on each new instance under PER_METHOD, which costs almost nothing. What the lifecycle does not do is reset the beans inside the cached context: a singleton service holding state keeps it across tests, which is the actual source of most flakiness in Spring suites, and the cure is @DirtiesContext sparingly, rolling back transactions or resetting the beans in @BeforeEach.

Rules to keep tests independent

  1. Default to PER_METHOD and build a fresh object under test in each test or in @BeforeEach.
  2. Make fields private final where you can; a field that is never reassigned cannot leak a change.
  3. Never rely on the order of tests, with or without @TestMethodOrder. Use ordering only for tests that are explicitly steps of a scenario, and say so.
  4. Treat static mutable fields as a smell and justify each one.
  5. Clean up what a test creates in external systems, in @AfterEach, not in the next test's setup.
  6. Run a single test method on its own in CI sometimes, with a random order, to flush out hidden dependencies: JUnit's MethodOrderer.Random helps.
java
@TestMethodOrder(MethodOrderer.Random.class)
class OrderServiceTest { /* ... */ }

A suite that passes in random order is a suite whose tests do not depend on each other.

When this does not apply

If your tests are pure functions of their inputs, with no shared fields, the lifecycle makes no difference and you can ignore this entire topic. If you use extensions that manage resources, such as Testcontainers' @Container, the extension decides where the resource lives, a static field starts a container once per class and an instance field once per test, and the same sharing rules apply to it. The primary reference is the JUnit user guide on test instance lifecycle, and the migration notes between versions are in upgrading from JUnit 5 to 6. The Jupiter API reference is on the JUnit Javadoc site.

Taggedexplainer
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.