JUnit 5 @TestInstance(Lifecycle.PER_CLASS) Parallel Execution: Thread Safety Uncertainty
0 reputation · 16 Jun 2021, 18:01 UTC
Background
The @TestInstance(Lifecycle.PER_CLASS) annotation creates a single test class instance reused across all test methods. This differs from the default PER_METHOD lifecycle, which instantiates a fresh object for each test.
Unresolved Concern
When parallel execution is enabled on the JUnit Platform, test methods may run concurrently. The documentation does not assert whether the single instance created by PER_CLASS is automatically serialized or if shared mutable state becomes a race condition.
Goal
Determine the behavior of PER_CLASS under parallel execution and the implications for thread safety and method ordering.
Key Questions
- Does JUnit automatically serialize test method execution for
PER_CLASSwhen parallel execution is enabled? - If serialization is not guaranteed, what patterns can developers adopt to ensure thread safety?
- How does nested or parameterized test structure affect the lifecycle callbacks and potential concurrency issues?