Testing / JUnit6 Interview Questions
What is the TestInstance lifecycle in JUnit 6 and what are the two modes?
By default JUnit 6 creates a new test class instance for each test method (PER_METHOD). The @TestInstance annotation lets you change this to PER_CLASS, where one instance is shared across all methods in the class.
| Mode | Annotation | Behaviour | Implication |
|---|---|---|---|
| PER_METHOD (default) | None needed | New instance per @Test method | Test isolation guaranteed; @BeforeAll/@AfterAll must be static |
| PER_CLASS | @TestInstance(Lifecycle.PER_CLASS) | Single instance for entire class | Instance state can accumulate across tests; @BeforeAll/@AfterAll can be non-static |
// PER_METHOD (default): new instance per test class DefaultLifecycleTest { int counter = 0; @Test void firstTest() { counter++; assertEquals(1, counter); } @Test void secondTest() { counter++; assertEquals(1, counter); } // passes! // Each test gets a fresh instance with counter=0 } // PER_CLASS: single shared instance @TestInstance(TestInstance.Lifecycle.PER_CLASS) class SharedInstanceTest { int counter = 0; @Test void firstTest() { counter++; assertEquals(1, counter); } @Test void secondTest() { counter++; assertEquals(2, counter); } // passes! // Shared instance: counter carries over // @BeforeAll and @AfterAll can be non-static: @BeforeAll void initAll() { System.out.println("Runs once, non-static -- only possible with PER_CLASS"); } } // PER_CLASS is common for @Nested tests where // the outer class must hold shared state accessed by inner classes.
More Related questions...