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.