JUnit 5 default lifecycle requires static @BeforeAll and @AfterAll
0 reputation · 30 Jun 2023, 07:21 UTC
A JUnit 5 test class requires non-static @BeforeAll and @AfterAll methods so setup can use constructor-injected dependencies. Under the default lifecycle, JUnit 5 instantiates the test class once per test method and rejects non-static class-level lifecycle methods.
Enabling @TestInstance(TestInstance.Lifecycle.PER_CLASS) reuses a single instance for all tests in the class. That removes the static restriction, but it also means @BeforeEach, test methods, and @AfterEach share the same object. Instance fields may retain values across tests, and parallel execution may expose thread-safety issues that are not present with per-method instances.
- Does PER_CLASS bind @BeforeAll, @BeforeEach, test methods, @AfterEach, and @AfterAll to the same test instance?
- What is the supported way to reset mutable instance fields between tests while keeping PER_CLASS?
- Is a PER_CLASS test instance safe for concurrent execution when multiple test methods run on parallel threads?