Verify custom extension execution in JUnit 5
Preconditions (2)
✅ Expected Result: The custom extension's beforeEach method is executed before the test method, and the test passes
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.BeforeEachCallback; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.ExtendWith; import static org.junit.jupiter.api.Assertions.assertTrue; class CustomExtension implements BeforeEachCallback { static boolean beforeEachCalled = false; @Override public void beforeEach(ExtensionContext context) { beforeEachCalled = true; System.out.println("CustomExtension beforeEach called"); } } @ExtendWith(CustomExtension.class) public class ExtensionModelTest { @Test void testWithExtension() { assertTrue(CustomExtension.beforeEachCalled, "Extension beforeEach should be called before test"); } }
The CustomExtension class implements BeforeEachCallback to run code before each test method.
We use a static boolean beforeEachCalled to track if the extension method runs.
The test class ExtensionModelTest registers the extension with @ExtendWith.
The test method asserts that the extension's beforeEach method was called before the test runs.
This shows how JUnit 5 extensions can add behavior around tests.
Now add a second extension that implements AfterEachCallback and verify it runs after the test method
@ExtendWith to apply extensions to test classes or methods.@ExtendWith(MyExtension.class)
class MyTest {
@Test
void testMethod() {
System.out.println("Test running");
}
}
class MyExtension implements BeforeTestExecutionCallback {
public void beforeTestExecution(ExtensionContext context) {
System.out.println("Before test");
}
}BeforeTestExecutionCallback runs its method before the test method executes, printing "Before test" first.public class MyExtension implements BeforeTestExecutionCallback {
public void beforeTestExecution() {
System.out.println("Before test");
}
}BeforeTestExecutionCallback requires beforeTestExecution(ExtensionContext context) method with one parameter.BeforeEachCallback runs before each test method, and AfterEachCallback runs after each test method.BeforeEachCallback and AfterEachCallback.Pass the test and this pattern moves unknown