The extension model in JUnit helps you add extra features to your tests easily. It lets you run code before or after tests, change how tests behave, and share setup steps.
0
0
Extension model overview in JUnit
Introduction
You want to run some code before or after each test automatically.
You need to change how tests are run without changing the test code itself.
You want to add custom behavior like retrying failed tests or logging extra info.
You want to share common setup or cleanup steps across many tests.
You want to control test execution order or conditions dynamically.
Syntax
JUnit
@ExtendWith(YourExtension.class) public class YourTestClass { // test methods }
Use @ExtendWith annotation to register an extension on a test class or method.
Extensions implement interfaces like BeforeEachCallback, AfterEachCallback, etc.
Examples
This example uses a custom extension to measure test execution time.
JUnit
@ExtendWith(TimingExtension.class) public class MyTests { @Test void testExample() { // test code } }
This shows a retry extension that can rerun a test if it fails.
JUnit
public class RetryExtension implements TestExecutionExceptionHandler { @Override public void handleTestExecutionException(ExtensionContext context, Throwable throwable) throws Throwable { // retry logic here } } @ExtendWith(RetryExtension.class) public class RetryTests { @Test void flakyTest() { // test that might fail sometimes } }
Sample Program
This test class uses a simple extension that prints messages before and after each test runs.
JUnit
import org.junit.jupiter.api.extension.*; import org.junit.jupiter.api.*; class SimpleExtension implements BeforeEachCallback, AfterEachCallback { @Override public void beforeEach(ExtensionContext context) { System.out.println("Starting test: " + context.getDisplayName()); } @Override public void afterEach(ExtensionContext context) { System.out.println("Finished test: " + context.getDisplayName()); } } @ExtendWith(SimpleExtension.class) public class ExtensionModelTest { @Test void testOne() { Assertions.assertTrue(true); } @Test void testTwo() { Assertions.assertEquals(2, 1 + 1); } }
OutputSuccess
Important Notes
Extensions can be reused across many test classes to keep code clean.
JUnit provides many built-in extension points like lifecycle callbacks and parameter resolvers.
Custom extensions must implement specific interfaces depending on what they do.
Summary
The extension model lets you add extra behavior to tests without changing test code.
Use @ExtendWith to apply extensions to tests.
Extensions can run code before/after tests, handle exceptions, or change test execution.