Automate a JUnit 5 test using @ExtendWith to register a custom extension
Preconditions (2)
✅ Expected Result: The test runs successfully with the custom extension applied, and the assertion passes
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.Extension; import org.junit.jupiter.api.extension.BeforeEachCallback; import org.junit.jupiter.api.extension.ExtensionContext; import static org.junit.jupiter.api.Assertions.assertTrue; // Custom extension that prints a message before each test class MyCustomExtension implements BeforeEachCallback { @Override public void beforeEach(ExtensionContext context) { System.out.println("Custom extension before each test method: " + context.getDisplayName()); } } @ExtendWith(MyCustomExtension.class) public class MyTestWithExtension { @Test void testExample() { assertTrue(true, "True should be true"); } }
This code defines a custom extension MyCustomExtension that implements BeforeEachCallback. It prints a message before each test method runs.
The test class MyTestWithExtension is annotated with @ExtendWith(MyCustomExtension.class) to register the extension.
The test method testExample simply asserts true is true, which always passes.
When running the test, the extension's beforeEach method runs first, printing the message, then the test runs and passes.
Now add data-driven testing with 3 different inputs to the test method using @ParameterizedTest and @ValueSource
@ExtendWith annotation in JUnit 5?@ExtendWith@Test mark test methods, but @ExtendWith is specifically for extensions.@ExtendWith to register a custom extension named MyExtension.class on a test class?@ExtendWith(MyExtension.class).@ExtendWith(MyExtension.class)
public class SampleTest {
@Test
void testMethod() {
System.out.println("Test running");
}
}
class MyExtension implements BeforeTestExecutionCallback {
public void beforeTestExecution(ExtensionContext context) {
System.out.println("Before test");
}
}MyExtension implements BeforeTestExecutionCallback, so it runs code before the test method.@ExtendWith:@ExtendWith
public class FaultyTest {
@Test
void testSomething() {}
}@ExtendWith usage@ExtendWith(MyExtension.class).@ExtendWith to achieve this cleanly?BeforeEachCallback allows running code before each test method.@ExtendWith on test classes@ExtendWith(YourExtension.class) reuses the setup logic cleanly across classes.@BeforeAll is less reusable or runs only once per class. Annotating methods individually is repetitive.Pass the test and this pattern moves unknown