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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
