Testing / JUnit6 Interview Questions
What are the Extension Model and extension points in JUnit 6?
JUnit 6 uses a single, composable Extension Model replacing JUnit 4's fragmented @RunWith, @Rule, and @ClassRule system. Extensions implement one or more callback interfaces corresponding to specific points in the test lifecycle.
| Interface | Callback method | When it executes |
|---|---|---|
| BeforeAllCallback | beforeAll(ExtensionContext) | Before all tests in the class |
| BeforeEachCallback | beforeEach(ExtensionContext) | Before each test method |
| BeforeTestExecutionCallback | beforeTestExecution(ExtensionContext) | Just before the test method body |
| AfterTestExecutionCallback | afterTestExecution(ExtensionContext) | Just after the test method body |
| AfterEachCallback | afterEach(ExtensionContext) | After each test method (including cleanup) |
| AfterAllCallback | afterAll(ExtensionContext) | After all tests in the class |
| TestInstancePostProcessor | postProcessTestInstance(...) | After test instance creation |
| ParameterResolver | supportsParameter + resolveParameter | Inject custom parameters into test methods |
// Custom extension: time each test and log slow ones @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @ExtendWith(TimingExtension.class) public @interface Timed { long thresholdMs() default 100; } public class TimingExtension implements BeforeTestExecutionCallback, AfterTestExecutionCallback { private static final String START = "start_time"; @Override public void beforeTestExecution(ExtensionContext ctx) { ctx.getStore(GLOBAL).put(START, System.currentTimeMillis()); } @Override public void afterTestExecution(ExtensionContext ctx) { long start = ctx.getStore(GLOBAL).remove(START, long.class); long elapsed = System.currentTimeMillis() - start; Timed ann = ctx.getRequiredTestMethod().getAnnotation(Timed.class); if (ann != null && elapsed > ann.thresholdMs()) { System.out.printf("[SLOW] %s took %dms%n", ctx.getDisplayName(), elapsed); } } } // Usage: @Test @Timed(thresholdMs = 200) void slowIntegrationTest() { ... }
More Related questions...