RepeatedTest with @TestInstance(PER_CLASS) yields varying instance IDs
0 reputation · 23 Feb 2024, 10:03 UTC
0 reputation · 23 Feb 2024, 10:03 UTC
Determine whether JUnit 5’s @RepeatedTest annotation creates a new test instance for each repetition when the test class is annotated with @TestInstance(Lifecycle.PER_CLASS).
The current specification does not explicitly state if the same instance should be reused across repetitions, and the behavior is still under discussion in the project’s issue tracker. Relying on the observed instance‑creation pattern may lead to flaky tests if the API changes in a future release.
Does JUnit 5 currently instantiate a new test object for each repetition under @TestInstance(PER_CLASS)? If the instance is reused, what conditions trigger reuse? Is there any version‑specific guarantee that the behavior will remain stable?
28775 reputation · 23 Feb 2024, 14:12 UTC
In a standard JUnit 5 test run, the @TestInstance(Lifecycle.PER_CLASS) annotation tells the engine to create a single instance of the test class and reuse it for all test methods, including repetitions. In practice, the same object is invoked for every repetition, so System.identityHashCode(this) will stay constant across all @RepeatedTest executions.
@RepeatedTest to bypass the PER_CLASS lifecycle, resulting in a fresh instance per repetition.TestInstancePostProcessor or use @ExtendWith may force a new instance per invocation.@TestInstance(PER_CLASS) inside the nested class.System.identityHashCode(this) inside the @RepeatedTest method.
@RepeatedTest(5)
void testRepeat() {
System.out.println("Instance hash: " + System.identityHashCode(this));
}
@ExtendWith extension that might override the lifecycle? Temporarily remove the extension.
mvn -q -Dexec.executable=echo -Dexec.args='%{project.version}' --non-recursive exec:exec or inspect the IDE’s dependency tree.
@TestInstance(PER_CLASS) as well.
To provide a definitive recommendation, could you share the exact JUnit 5 and JUnit Platform versions you are using? This will confirm whether the current release guarantees instance reuse across repetitions.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.