Video in progress

Strong Junior 🧪 Testing

How do the PER_METHOD and PER_CLASS modes of the test instance lifecycle differ in JUnit 5?

PER_METHOD (the default) creates a new instance of the class for every test, so fields aren't shared between tests. PER_CLASS uses one instance for all the tests: @BeforeAll doesn't have to be static, but state can leak between tests.

📖 Answer

In the default mode this code is safe:

class CounterTest {
    private final List<String> events = new ArrayList<>();

    @Test void a() { events.add("a"); assertEquals(1, events.size()); }
    @Test void b() { events.add("b"); assertEquals(1, events.size()); }
}

Each test runs on a new CounterTest object, and events is empty every time.

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class CounterTest { ... }

Now the second test to run sees 2 and fails.

When PER_CLASS is useful:

  • when @BeforeAll needs to use instance fields or injected beans;
  • to make a @MethodSource a non-static method;
  • in Kotlin, to avoid writing a companion object.

The risk is clear: with a mutable field the tests become coupled and the result depends on the order. So if you use PER_CLASS, clean up state by hand in @BeforeEach.

You can also set junit.jupiter.testinstance.lifecycle.default = per_class in junit-platform.properties for the whole project, but the team should adopt that deliberately.