What is the primary purpose of the @ExtendWith annotation in JUnit 5?
Think about how JUnit 5 allows adding extra features to tests beyond basic assertions.
The @ExtendWith annotation is used to register extensions in JUnit 5. Extensions can add extra behavior like lifecycle callbacks, parameter resolution, or conditional test execution.
Given the following JUnit 5 test code using @ExtendWith, what will be printed when the test runs?
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.*; class MyExtension implements BeforeTestExecutionCallback { @Override public void beforeTestExecution(ExtensionContext context) { System.out.println("Before test: " + context.getDisplayName()); } } @ExtendWith(MyExtension.class) class SampleTest { @Test void testMethod() { System.out.println("Inside test method"); } }
Consider when the beforeTestExecution callback runs relative to the test method.
The beforeTestExecution method runs just before the test method. So the extension prints its message first, then the test method prints its message.
Which assertion correctly verifies that a test class is registered with a specific extension using @ExtendWith in JUnit 5?
Check how to verify if an annotation is present on a class.
The isAnnotationPresent method returns true if the annotation is present. This is the best way to assert that @ExtendWith is used.
A developer uses @ExtendWith(MyExtension.class) on a test class, but the extension's methods are never called during test execution. What is the most likely cause?
Think about what JUnit 5 requires for an extension to be recognized and invoked.
JUnit 5 calls extension methods only if the extension class implements one or more extension interfaces like BeforeTestExecutionCallback. Without implementing these, the extension has no effect.
Consider a test class annotated with @ExtendWith({ExtA.class, ExtB.class}). Which statement about the order of extension callbacks is true?
Think about how JUnit 5 processes multiple extensions declared together.
JUnit 5 invokes extension callbacks in the order they are declared in the @ExtendWith annotation. So ExtA runs before ExtB.