Test Overview
This test uses the @ExtendWith annotation in JUnit 5 to register a custom extension. It verifies that the extension's callback method is called during test execution.
This test uses the @ExtendWith annotation in JUnit 5 to register a custom extension. It verifies that the extension's callback method is called during test execution.
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.assertTrue; class MyExtension implements BeforeEachCallback { static boolean beforeEachCalled = false; @Override public void beforeEach(ExtensionContext context) { beforeEachCalled = true; } } @ExtendWith(MyExtension.class) public class ExtendWithTest { @Test void testExtensionCalled() { assertTrue(MyExtension.beforeEachCalled, "Extension beforeEach should have been called"); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | JUnit test runner starts the test class ExtendWithTest | JUnit framework initialized, test class loaded | — | PASS |
| 2 | JUnit detects @ExtendWith(MyExtension.class) and registers MyExtension as an extension | Extension MyExtension is ready to be called before each test | — | PASS |
| 3 | JUnit calls MyExtension.beforeEach() before running testExtensionCalled() | MyExtension.beforeEachCalled is set to true | — | PASS |
| 4 | JUnit runs testExtensionCalled() method | Test method executing | assertTrue(MyExtension.beforeEachCalled) verifies beforeEachCalled is true | PASS |
| 5 | JUnit completes testExtensionCalled() successfully | Test passed | — | PASS |
@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