Why do developers use extensions to customize JUnit behavior?
Think about how extensions help tests do more than just run assertions.
JUnit extensions allow adding features such as custom setup/teardown, injecting parameters, or modifying test execution flow, enhancing test flexibility.
Given the following JUnit 5 extension and test, what will be the output when the test runs?
import org.junit.jupiter.api.extension.*; import org.junit.jupiter.api.*; class SkipTestExtension implements ExecutionCondition { @Override public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) { if (context.getDisplayName().contains("skip")) { return ConditionEvaluationResult.disabled("Test skipped by extension"); } return ConditionEvaluationResult.enabled("Test enabled"); } } @ExtendWith(SkipTestExtension.class) class SampleTest { @Test void testRun() { System.out.println("Test is running"); } @Test void test_skip() { System.out.println("This should not print"); } }
Look at how the extension disables tests with 'skip' in their name.
The extension disables tests whose display name contains 'skip'. So 'test_skip' is skipped and does not print. 'testRun' runs normally.
Which assertion correctly verifies that a JUnit extension has injected a non-null parameter into a test method?
@ExtendWith(MyParameterResolver.class)
void testWithParam(String param) {
// Which assertion to use here?
}Parameter injection should provide a valid object, not null.
To verify parameter injection worked, assert the parameter is not null. Other assertions check for null or empty, which are incorrect here.
A custom JUnit extension intended to log before each test is not printing logs. What is the most likely cause?
public class LoggingExtension implements BeforeTestExecutionCallback { @Override public void beforeTestExecution(ExtensionContext context) { System.out.println("Starting test: " + context.getDisplayName()); } } // Test class missing @ExtendWith(LoggingExtension.class)
Check if the extension is properly registered with the test class.
Extensions must be registered with @ExtendWith on the test class or method to be active. Without it, the extension code won't run.
Which JUnit 5 extension point allows modifying the test instance after it is created but before any tests run?
Think about the extension that can change the test object itself after creation.
TestInstancePostProcessor lets you modify or initialize the test instance after construction but before tests run. Others serve different purposes.