JUnit Extension
Definition
A JUnit Extension is the Jupiter replacement for a JUnit 4 Rule. You implement callbacks such as BeforeEachCallback or AfterAllCallback, then register the extension with @ExtendWith on a class or with a @RegisterExtension field. Extensions wrap test execution the same way Rules did: shared setup, cleanup, parameter injection, and extra conditions, without copying setUp into every class. Current JUnit 6 docs still use this model on the JUnit Platform.
Key Takeaways
- New tests on JUnit 5 or 6 should use Extensions, not
org.junit.Rule. @ExtendWithis declarative.@RegisterExtensionis the instance-field style closest to@Rule.@TempDir,assertThrows,@Timeout, andTestInforeplace the old built-in rules.- Spring Boot and Mockito register their own extensions instead of JUnit 4 rules.
How It Works
- Jupiter looks for registered extensions and calls their callbacks around each test or class.
ExtensionContextgives you the test class, method, and a store for per-test state.- You can implement several callback interfaces on one class if you need before and after.
- JUnit Vintage can still run old Rules on the platform, but it is a migration path, not the long-term API.
Where It Is Used
@ExtendWith(SpringExtension.class)or@SpringBootTestwires the Spring test context.@ExtendWith(MockitoExtension.class)initializes@Mockfields.- A
DatabaseResetExtensionthat implementsBeforeEachCallbackis the direct port of aDatabaseResetRule.