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 { ... }
More Related questions...