Testing / JUnit6 Interview Questions
What is the difference between @ExtendWith and @RegisterExtension in JUnit 6?
JUnit 6 provides two ways to register extensions. The choice between them depends on whether you need programmatic construction (with constructor arguments) or simple declarative annotation use.
| Aspect | @ExtendWith | @RegisterExtension |
|---|---|---|
| Location | Annotation on class or method | Field in the test class |
| Extension construction | JUnit calls default no-arg constructor | Developer constructs with custom arguments |
| When to use | Stateless extensions with no configuration | Extensions that need constructor parameters or runtime configuration |
| Lifecycle control | Limited | Full: static field = class scope; instance field = method scope |
| Example | @ExtendWith(MockitoExtension.class) | @RegisterExtension static WireMockExtension wm = WireMockExtension.newInstance().port(8080).build(); |
// @ExtendWith: declarative, no constructor args @ExtendWith(MockitoExtension.class) class MockitoTest { @Mock UserRepository repo; @Test void test() { ... } } // @RegisterExtension: programmatic, with constructor args class WireMockTest { // Static field -> class-scoped lifecycle (like @BeforeAll/@AfterAll) @RegisterExtension static WireMockExtension wireMock = WireMockExtension.newInstance() .options(wireMockConfig().port(8080)) .build(); // Instance field -> method-scoped lifecycle (fresh per test) @RegisterExtension DatabaseExtension db = new DatabaseExtension("jdbc:h2:mem:test"); @Test void callsExternalService() { wireMock.stubFor(get("/api/users").willReturn(okJson("[]"))); // ... } } // Multiple extensions can be combined: @ExtendWith({MockitoExtension.class, SpringExtension.class}) class SpringMockitoTest { ... }
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...
