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 |
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...
