Testing / JUnit6 Interview Questions
What is @TestInstance and how does it change test class lifecycle?
By default, JUnit creates a new instance of the test class for each test method. @TestInstance(Lifecycle.PER_CLASS) changes this so a single instance is shared across all test methods in the class.
// Default: PER_METHOD (new instance per test) class DefaultLifecycleTest { int count = 0; @Test void first() { count++; assertEquals(1, count); } // pass @Test void second() { count++; assertEquals(1, count); } // pass // Each @Test gets its own instance, so count starts at 0 each time } // PER_CLASS: single shared instance @TestInstance(TestInstance.Lifecycle.PER_CLASS) class SharedInstanceTest { int count = 0; @Test @Order(1) void first() { count++; assertEquals(1, count); } @Test @Order(2) void second() { count++; assertEquals(2, count); } // Same instance: count accumulates across tests // Benefits of PER_CLASS: // 1. @BeforeAll and @AfterAll can be NON-STATIC @BeforeAll void setUpAll() { // no static required! database = Database.connect(); } @AfterAll void tearDownAll() { // no static required! database.close(); } // 2. Shared expensive state (database, server) // without static fields Database database; }
| Aspect | PER_METHOD (default) | PER_CLASS |
|---|---|---|
| Instances created | One per test method | One per test class |
| @BeforeAll/@AfterAll must be | static | Can be non-static |
| Test isolation | High (fresh instance per test) | Lower (shared mutable state) |
| Use case | Unit tests | Integration tests with shared expensive resources |
More Related questions...