One instance per class

By default Jupiter builds a new test object for every test method, and that is what makes a field safe: each test gets its own. @TestInstance(PER_CLASS) changes the rule to one object for the class, which lets a class-level method be non-static and lets a test build a value that the next test can use. The price is the state that the default was protecting you from.

The two lifecycles

PER_METHOD is the default: one instance per test method, a new instance for each. A field written by one test is invisible to the next, and a @BeforeAll has no instance to work on, so it must be static.

PER_CLASS is the other mode: one instance for the class, reused by every test. A @BeforeAll can be an ordinary instance method, and a field written by one test is still there for the next. The mode is a class annotation: @TestInstance(TestInstance.Lifecycle.PER_CLASS).

One instance per class

SharedTest.java sets a field in a non-static @BeforeAll and two tests read it. Neither test writes to the field, so the order of the two does not matter.

import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; @TestInstance(TestInstance.Lifecycle.PER_CLASS) public class SharedTest { private String name; @BeforeAll void setUp() { name = "shared"; } @Test void firstTestSeesTheValue() { assertEquals("shared", name); } @Test void secondTestSeesTheValue() { assertEquals("shared", name); } }

A non-static @BeforeAll

The same method in the default mode would be rejected with Non-static @BeforeAll method ... must be static unless the test class is annotated with @TestInstance(PER_CLASS). With the annotation the method has an instance to belong to, and it runs once before the first test.

@AfterAll loses the static rule the same way. That is convenient for a fixture that is an object field with a close method, but the object now lives for the whole class, so its state survives between tests.

Shared state

The per-class mode turns every field into a field shared by all the tests. A test that adds to a list changes what the next test sees, and the report does not say which order the tests ran in. The mode is right for an expensive resource that is read-only after setup, and wrong for a fixture that every test should get fresh.

When the state is unavoidable, reset it in @BeforeEach, which still runs before every test in this mode. The class instance is shared; the before-each method is the place to put it back into a known shape.

The report

javac -Xlint:all -cp /opt/java-tools/junit-platform-console-standalone.jar -d out SharedTest.java
junit execute --class-path out --scan-classpath --disable-ansi-colors

Thanks for using JUnit! Support its development at https://junit.org/sponsoring

╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
│  └─ SharedTest ✔
│     ├─ secondTestSeesTheValue() ✔
│     └─ firstTestSeesTheValue() ✔
└─ JUnit Vintage ✔

Test run finished after 439 ms
[         4 containers found      ]
[         0 containers skipped    ]
[         4 containers started    ]
[         0 containers aborted    ]
[         4 containers successful ]
[         0 containers failed     ]
[         2 tests found           ]
[         0 tests skipped         ]
[         2 tests started         ]
[         0 tests aborted         ]
[         2 tests successful      ]
[         0 tests failed          ]

The tree lists the methods in the launcher's order, not in source order: the second test is printed first. Both pass because neither test changes the field. A third test that appended to a list would pass or fail depending on where it landed, which is the risk the default mode removes.

Exercises

  1. Remove the annotation and run. Copy the exception line that names the non-static method.
  2. Add a test that writes name = "changed", run twice, and compare the two reports. Is the failure stable?
  3. Add an @AfterAll instance method that clears the field. Does it compile without the annotation?
  4. Move the setup into @BeforeEach and delete the annotation. Which lifecycle does the class need now, and why?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does @TestInstance(PER_CLASS) change?

    Answer

    Jupiter creates one test instance for the whole class

    The per-class lifecycle reuses one object, so its fields are shared by every test.

  2. Which method can be non-static only in the per-class mode?

    Answer

    @BeforeAll

    The class-level methods need an instance, which the default lifecycle does not keep.

  3. What is the risk of the per-class lifecycle?

    Answer

    State written by one test is seen by the next, and the order is not guaranteed

    A shared object keeps its fields, so one test can change what another reads.

  4. What does this program print? public class Q1 { public static void main(String[] args) { String name = "shared"; System.out.println(name); } }

    Answer

    shared

    println prints the value of the string, which is shared.

  5. What does this program print? public class Q2 { public static void main(String[] args) { int first = 1; int second = 2; System.out.println(first + second); } }

    Answer

    3

    The two integers are added, and the sum is 3.

  6. What does this program print? public class Q3 { public static void main(String[] args) { StringBuilder text = new StringBuilder("a"); text.append("b"); System.out.println(text.toString()); } }

    Answer

    ab

    append adds b to the same builder, and toString returns ab.

  7. What does this program print? public class Q4 { public static void main(String[] args) { String name = "Ada"; name = name.toUpperCase(); System.out.println(name); } }

    Answer

    ADA

    toUpperCase returns ADA, and the assignment stores it in name.

  8. In the default lifecycle, why is a field initialized in its declaration safe?

    Answer

    Jupiter creates a new test instance for every test method

    A new instance per test means the field starts from its initializer for every test.

  9. What does this program print? public class Q5 { public static void main(String[] args) { int n = 2; n = n * 3; System.out.println(n); } }

    Answer

    6

    The multiplication gives 6, and println prints it.

  10. Where should a shared field be reset in the per-class mode?

    Answer

    In @BeforeEach, which still runs before every test

    The per-test hook already exists and restores the known state before each test.

The code on this page was built with OpenJDK 21.0.13 (javac) and run with JUnit Platform Console Launcher 1.14.3 on Alpine Linux in a Docker container.

Article author: Arthur Isaev