JUnit Extension
Also known as:
JUnit 5 Extension
Jupiter Extension
@ExtendWith
@RegisterExtension
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.
Popular reads
View All
Payment System Design: Ledger, Idempotency, and Settlement
Jul 18, 2026
The Complete HTMX Guide: From Zero to Production
Dec 22, 2025
How Google manages billions of lines of code in one monorepo
Sep 04, 2026
Transactional Outbox Pattern: Never Lose an Event Again
Apr 07, 2026
Cursor Skills: How to Create and Use Agent Skills
Jun 23, 2026
Git Flow vs GitHub Flow
Jun 05, 2026
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.