Verify custom JUnit extension modifies test behavior
Preconditions (2)
✅ Expected Result: The test method runs with the custom behavior applied by the extension, verified by assertions or output changes
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.BeforeEachCallback; import org.junit.jupiter.api.extension.ExtensionContext; import static org.junit.jupiter.api.Assertions.assertEquals; // Custom extension that sets a value before each test class CustomValueExtension implements BeforeEachCallback { @Override public void beforeEach(ExtensionContext context) { context.getStore(ExtensionContext.Namespace.GLOBAL).put("value", 42); } } @ExtendWith(CustomValueExtension.class) public class CustomExtensionTest { @Test void testValueSetByExtension(ExtensionContext context) { Integer value = context.getStore(ExtensionContext.Namespace.GLOBAL).get("value", Integer.class); assertEquals(42, value, "Extension should set value to 42 before each test"); } @Test void testAnotherValueCheck(ExtensionContext context) { Integer value = context.getStore(ExtensionContext.Namespace.GLOBAL).get("value", Integer.class); assertEquals(42, value); } }
This code defines a custom JUnit 5 extension CustomValueExtension that implements BeforeEachCallback. It sets a value of 42 in the global store before each test runs.
The test class CustomExtensionTest uses @ExtendWith(CustomValueExtension.class) to apply the extension. Each test method accesses the stored value from the extension context and asserts it equals 42.
This shows how extensions customize JUnit behavior by injecting or modifying test state before execution. Assertions verify the extension's effect, ensuring the test passes only if the extension works correctly.
Now add data-driven testing with 3 different values set by the extension
@ExtendWith.@ExtendWith(MyExtension.class)
class MyTest {
@Test
void testMethod() {
System.out.println("Test running");
}
}MyExtension prints "Before test" before the test and "After test" after the test.@ExtendWith(MyExtension.class)
class TestClass {
@Test
void test() {
System.out.println("Running test");
}
void helper() {
System.out.println("Helper method");
}
}helper() not be called during test execution?@Test run as tests; helper() lacks this annotation.BeforeEachCallback interface allows running code before each test method.beforeEach() method is the correct way to customize data before tests.Pass the test and this pattern moves unknown