Testing / JUnit6 Interview Questions
What is the ExtensionContext and its Store used for in JUnit 6?
The ExtensionContext is the primary object through which extensions interact with the JUnit 6 runtime. It provides access to the current test method, class, display name, tags, and a key-value Store for sharing data between extension callbacks.
// ExtensionContext.Store: share data between callbacks within an extension public class TimingExtension implements BeforeTestExecutionCallback, AfterTestExecutionCallback { // Namespace prevents collisions between multiple extensions private static final Namespace NS = Namespace.create(TimingExtension.class); @Override public void beforeTestExecution(ExtensionContext ctx) { // Store the start time under this test's context getStore(ctx).put("startTime", System.currentTimeMillis()); } @Override public void afterTestExecution(ExtensionContext ctx) { long startTime = getStore(ctx).remove("startTime", long.class); long elapsed = System.currentTimeMillis() - startTime; System.out.printf("%s took %d ms%n", ctx.getDisplayName(), elapsed); } private ExtensionContext.Store getStore(ExtensionContext ctx) { return ctx.getStore(NS); } } // ExtensionContext key methods: // ctx.getDisplayName() -- test display name // ctx.getRequiredTestMethod() -- the @Test Method object // ctx.getRequiredTestClass() -- the test class // ctx.getTags() -- Set<String> of @Tag values // ctx.getTestInstance() -- Optional<Object> test instance // ctx.getCancellationToken() -- JUnit 6: cooperative cancellation // ctx.getStore(namespace) -- scoped key-value store // ctx.getRoot() -- root context (global scope)
More Related questions...