Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

In JUnit 5, how many instances of a test class are created by default, and what changes with @TestInstance(Lifecycle.PER_CLASS)?

By default JUnit Jupiter creates a new instance of the test class for every test method it runs, so a class with three tests gets three instances and instance fields never leak from one test to the next. Because no instance exists before the first test, @BeforeAll and @AfterAll methods must be static. With @TestInstance(Lifecycle.PER_CLASS), one instance is shared by all methods of the class, @BeforeAll and @AfterAll can be ordinary instance methods, and the price is that state in fields now carries over between tests.

Why this question is asked

Most of us write test classes for years without asking how many objects JUnit creates, until a field changed in one test shows up in another, or the compiler refuses a non-static @BeforeAll. Interviewers ask this because the answer explains test isolation, why some methods must be static, and when sharing an instance is worth the risk. In this answer, we will see the default per-method lifecycle in action, why it forces @BeforeAll to be static, what PER_CLASS changes, when PER_CLASS is a good idea, and how to change the default for a whole project.

1A Quick Recap of the Test Instance

A test class is an ordinary Java class, and its test methods are instance methods. To call an instance method, JUnit first needs an object, so it calls the class's constructor to create one. That object is the test instance. Fields we declare in the class, such as a list we fill during a test, belong to that object.

The question is simply how often JUnit calls the constructor. The answer controls whether two tests can see each other's field values.

2The Default: One Instance per Test Method

JUnit Jupiter's default is Lifecycle.PER_METHOD. Before each test method, and before each invocation of a repeated or parameterized test, it creates a brand-new instance. We can watch this happen by printing the object's identity in the constructor and in each test.

Java
class CounterTest {
private final List<String> items = new ArrayList<>();
CounterTest() { System.out.println("new instance " + System.identityHashCode(this)); }
@Test void addsOne() {
items.add("a");
assertEquals(1, items.size()); // passes: 1
}
@Test void addsAnother() {
items.add("b");
assertEquals(1, items.size()); // passes: 1, the list from addsOne is gone
}
}
// Output:
// new instance 1418428263
// new instance 2062448311 two tests, two instances

Notice that the second test sees an empty list even though the first test added to it. The first test's list belonged to a different object. So tests cannot leak state through instance fields, which is why the per-method lifecycle is the safe default: tests stay independent no matter which order they run in.

3Why @BeforeAll Must Be Static by Default

@BeforeAll runs once before any test in the class, and @AfterAll runs once after all of them. With the per-method lifecycle, at the moment @BeforeAll should run, no test instance exists yet, and there is no single instance that belongs to the whole class. So JUnit cannot call an instance method; it needs a static one.

Java
class RepositoryTest {
static Connection connection;
@BeforeAll
static void openConnection() throws SQLException { // static: no instance exists yet
connection = DriverManager.getConnection("jdbc:h2:mem:test");
}
@AfterAll
static void close() throws SQLException { connection.close(); }
// A non-static @BeforeAll here fails at runtime with an error saying
// the method must be static unless the class is annotated with
// @TestInstance(Lifecycle.PER_CLASS).
}

The data set up in @BeforeAll therefore lives in static fields, and anything static is shared by all tests on purpose.

4What PER_CLASS Changes

With @TestInstance(Lifecycle.PER_CLASS) on the class, JUnit creates one instance and runs every test method of the class on it. Since that instance exists before the first test, @BeforeAll and @AfterAll can be normal instance methods, and they can set ordinary fields. The same goes for @MethodSource factory methods, which may then be non-static.

Java
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class SharedInstanceTest {
private final List<String> items = new ArrayList<>();
private ExpensiveClient client;
@BeforeAll void start() { client = ExpensiveClient.connect(); } // non-static is allowed now
@AfterAll void stop() { client.close(); }
@Test void addsOne() { items.add("a"); }
@Test void addsAnother() {
items.add("b");
System.out.println(items.size()); // 2 if addsOne ran first, 1 otherwise
}
}
PER_METHOD against PER_CLASS
PER_METHOD (default)PER_CLASS
Instances for 3 tests31
@BeforeAll / @AfterAllmust be staticmay be instance methods
@MethodSource factorymust be staticmay be an instance method
Field state between testsnever sharedshared, reset it yourself

Here is the catch. The list now survives between tests, so the result of addsAnother depends on whether addsOne ran before it. That is order dependence, and it is exactly the class of bug the default lifecycle prevents. If we use PER_CLASS, we must reset mutable fields in @BeforeEach or keep only read-only shared objects in fields.

5When PER_CLASS Is Worth It

The first good use is expensive setup that we want to keep in instance fields, such as a client, a container or a large fixture that is read-only during tests. It reads more naturally than static fields, especially when that setup itself needs injected values. The second is Kotlin, which has no static methods without a companion object; PER_CLASS lets Kotlin tests declare @BeforeAll as a normal function. It is also handy with @Nested classes, which as inner classes cannot easily hold static methods in older Java versions.

What we should not do is use PER_CLASS so that one test can prepare data for the next. That turns a test suite into a script, and a single failure early in the class makes every later test fail for the wrong reason.

6Changing the Default for a Whole Project

If a project prefers PER_CLASS everywhere, for example a Kotlin code base, we do not need the annotation on every class. JUnit reads a configuration parameter, which we can put in src/test/resources/junit-platform.properties or pass as a system property.

Properties
# src/test/resources/junit-platform.properties
junit.jupiter.testinstance.lifecycle.default = per_class
# or on the command line for one build
./mvnw test -Djunit.jupiter.testinstance.lifecycle.default=per_class

A class can still override the default with its own @TestInstance annotation. Notice that this setting is invisible when reading a single test class, so a team that changes it should say so in its contributing guide; otherwise readers will assume the default per-method behaviour.

7Follow-up questions

Does JUnit create a new instance for each parameterized test invocation?

Yes, with the default lifecycle. Each invocation of a @ParameterizedTest or @RepeatedTest counts as its own test, so it gets its own instance, and @BeforeEach and @AfterEach run around each invocation.

Is Spring's application context created once per instance?

No. SpringExtension injects beans into each new test instance, but the application context itself is cached by the Spring TestContext framework and reused across instances and even across classes with the same configuration. So the per-method lifecycle does not make Spring tests slow; context creation does, and it is cached.

How did JUnit 4 behave?

JUnit 4 also created a new instance per test method, and @BeforeClass and @AfterClass had to be static. JUnit 4 had no option to share an instance, which is one of the things JUnit 5 added with @TestInstance.

8Conclusion

In this answer, we saw that JUnit Jupiter creates a new test instance for every test method by default, which keeps fields from leaking between tests and is why @BeforeAll and @AfterAll must be static. @TestInstance(Lifecycle.PER_CLASS) shares one instance across the class, allowing non-static @BeforeAll and @MethodSource methods, which helps with expensive setup and Kotlin, but it also lets mutable state create order dependence. The default for a project can be changed with junit.jupiter.testinstance.lifecycle.default.

What to say in the interviewAbout 80 seconds aloud

Open with

By default JUnit Jupiter uses the per-method lifecycle: it creates a new instance of the test class for every test method, and for every invocation of a parameterized or repeated test.

Then, if they want more

So if a class has three tests, the constructor runs three times, and anything I put in an instance field in one test is gone in the next. That is what keeps tests independent. The side effect is that @BeforeAll and @AfterAll must be static, because when they run there is no single instance that belongs to the whole class.

If I put @TestInstance(Lifecycle.PER_CLASS) on the class, JUnit creates one instance and runs all the methods on it. Then @BeforeAll and @AfterAll can be normal instance methods and @MethodSource factories can be non-static, which is nice for expensive setup kept in fields and almost necessary in Kotlin.

The risk is that mutable fields are now shared, so one test can change what the next one sees and the results start depending on order. I would reset mutable state in @BeforeEach or only keep read-only objects there. If a whole project wants per-class, I would set junit.jupiter.testinstance.lifecycle.default to per_class in junit-platform.properties and document it.

About this answer

Last updated
12 November 2026
Versions it names
JUnit 4, JUnit 5
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
JUnit user guide
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "In JUnit 5, how many instances of a test class are created by default, and what changes...": https://scrivio-interview-library.netlify.app/java/junit/d55be5a928/