Scrivio Interview library
ConceptFoundations5 min read · updated 12 November 2026

How does the JUnit 5 extension model replace JUnit 4 runners and rules? Give two built-in examples used in Spring projects.

In JUnit 5, behaviour around tests is added by extensions: classes that implement callback interfaces such as BeforeEachCallback, AfterEachCallback, ParameterResolver and TestExecutionExceptionHandler. They are registered declaratively with @ExtendWith, programmatically with @RegisterExtension, or automatically through Java's ServiceLoader. Unlike JUnit 4, where a class could have only one runner, many extensions can be combined; SpringExtension (used by @SpringBootTest) and MockitoExtension are the two everyday examples in Spring projects.

Why this question is asked

Every Spring test we write uses an extension, even if we never wrote one: @SpringBootTest quietly adds one. Understanding the extension model explains how Spring injects beans into test fields, how Mockito creates mocks, and why JUnit 5 combined these more easily than JUnit 4 ever could. Interviewers ask it to check that we know the mechanism, not just the annotations. In this answer, we will recap how JUnit 4 extended tests and what was wrong with it, see the extension points JUnit 5 offers, look at the three ways to register an extension, and see how SpringExtension and MockitoExtension use them.

1How JUnit 4 Added Behaviour and Why It Hurt

JUnit 4 had two mechanisms. A Runner took over the whole execution of a test class; @RunWith(SpringJUnit4ClassRunner.class) let Spring create the application context and inject fields. Rules, fields annotated with @Rule or @ClassRule, wrapped each test or the class in extra behaviour, such as a temporary folder.

The problem was that a class could have only one runner. A test that needed both Spring and Mockito, or Spring and a parameterized runner, had to pick one and work around the other, often with special rules such as SpringClassRule. Rules were also limited: they could wrap a test but could not, for example, supply parameters to a test method.

2Extension Points in JUnit 5

JUnit 5 replaced both with one idea: an extension is any class that implements one or more of the Extension sub-interfaces, and each interface is a hook at a specific point of the test lifecycle. JUnit calls every registered extension at each point.

Common extension points
InterfaceCalledTypical use
BeforeAllCallback / AfterAllCallbackonce per classstart and stop a server or container
BeforeEachCallback / AfterEachCallbackaround each test and its setupreset a clock, clean a table
TestInstancePostProcessorafter the instance is createdinject fields (@Autowired, @Mock)
ParameterResolverwhen a parameter needs a valueinject a bean, mock or fixture
TestExecutionExceptionHandlerwhen the test throwsadd diagnostics, translate errors
ExecutionConditionbefore runningskip in some environments

The most used hooks are the lifecycle callbacks: BeforeAllCallback, BeforeEachCallback, BeforeTestExecutionCallback and their After counterparts, which run code around the class, around each test including its @BeforeEach methods, or tightly around the test method itself. TestInstancePostProcessor lets an extension work on a new test instance, for example to inject fields. ParameterResolver lets an extension supply values for constructor and method parameters, which is how a test method can declare a parameter such as a TestInfo or a mock. TestExecutionExceptionHandler can inspect or swallow exceptions thrown by the test, and ExecutionCondition can decide to skip a test.

3Three Ways to Register an Extension

The declarative way is @ExtendWith on a class or method, and it can list several extensions. The order of declaration is the order in which before-callbacks run, and after-callbacks run in reverse. Annotations can be composed: @SpringBootTest is itself annotated with @ExtendWith(SpringExtension.class), so using it registers the extension.

Java
@ExtendWith({SpringExtension.class, MockitoExtension.class}) // two extensions on one class
class OrderServiceTest { }
class ApiTest {
@RegisterExtension // programmatic: we configure the instance
static WireMockExtension api = WireMockExtension.newInstance()
.options(wireMockConfig().dynamicPort())
.build();
}
// Automatic: listed in META-INF/services/org.junit.jupiter.api.extension.Extension
// and enabled with junit.jupiter.extensions.autodetection.enabled=true

@RegisterExtension is for extensions that need configuration in code, such as a WireMock server with a dynamic port; the field holds the extension instance, so tests can also call it. Static fields act at class level, instance fields at method level. Automatic registration through ServiceLoader applies an extension to every test on the classpath, but it is off by default and must be enabled with the configuration parameter shown above, because silent global behaviour can surprise people.

4SpringExtension and MockitoExtension in Action

SpringExtension integrates the Spring TestContext framework. It loads or reuses a cached application context before tests, injects @Autowired fields after the test instance is created, resolves constructor and method parameters from beans, and manages test transactions around each test. @SpringBootTest, @WebMvcTest, @DataJpaTest and the other test slices all register it for us.

MockitoExtension creates mocks for fields annotated with @Mock, injects them into @InjectMocks fields, can resolve @Mock parameters, and after each test checks for unnecessary stubbing in strict mode, reporting stubs we set up but never used.

Java
@ExtendWith(MockitoExtension.class)
class PricingServiceTest {
@Mock TaxClient taxClient; // created by MockitoExtension before each test
@InjectMocks PricingService service; // receives the mock
@Test void addsTax(@Mock AuditLog audit) { // ParameterResolver supplies this mock
when(taxClient.rate("GB")).thenReturn(new BigDecimal("0.20"));
assertEquals(new BigDecimal("12.00"), service.gross(new BigDecimal("10.00"), "GB")); // passes
}
}
Step throughExtensions called around one test
JUnitSpringExtensionMockitoExtensionTest
create test instance
postProcessTestInstance: inject beans
postProcessTestInstance: create @Mock fields
beforeEach: start test transaction
run @BeforeEach and @Test
afterEach: check strict stubs
afterEach: roll back transaction

7 messages in order. Play them, or step through them one at a time.

Because both are extensions, a test can use them together, which was the awkward case in JUnit 4. Other common ones are the Testcontainers extension, @TempDir support built into JUnit, and WireMock's extension.

5Follow-up questions

Can an extension keep state between callbacks?

Yes, but it should keep it in the ExtensionContext Store rather than in fields, because one extension instance may serve many tests, possibly in parallel. The Store is scoped to the current test or class and is cleaned up automatically.

Do I need @ExtendWith(SpringExtension.class) with @SpringBootTest?

No. @SpringBootTest and the test slice annotations are meta-annotated with @ExtendWith(SpringExtension.class), so adding it again is redundant, though harmless.

In what order do several extensions run?

Extensions registered on a class run in the order they are declared for before-callbacks and in reverse for after-callbacks, so the first registered wraps the others, like nested try-finally blocks.

6Conclusion

In this answer, we saw how JUnit 4's single runner and limited rules made combining behaviour awkward, and how JUnit 5 replaced them with extensions that implement focused callback interfaces such as BeforeEachCallback, ParameterResolver and TestExecutionExceptionHandler. Extensions are registered with @ExtendWith, @RegisterExtension or ServiceLoader auto-detection, and any number can be combined. SpringExtension and MockitoExtension are the everyday examples in Spring projects.

What to say in the interviewAbout 80 seconds aloud

Open with

In JUnit 4, you added behaviour with a runner or with rules, and a class could only have one runner, so combining Spring with Mockito or with parameterized tests was awkward.

Then, if they want more

JUnit 5 replaced both with the extension model. An extension is a class that implements one or more callback interfaces, each one a hook in the lifecycle: BeforeAllCallback and BeforeEachCallback and their After versions, TestInstancePostProcessor to work on a new test instance, ParameterResolver to supply method or constructor parameters, TestExecutionExceptionHandler to deal with exceptions, and ExecutionCondition to skip tests.

I register extensions with @ExtendWith, which can list several, with @RegisterExtension on a field when I need to configure the instance in code, like a WireMock server on a dynamic port, or automatically through ServiceLoader, which has to be switched on with a configuration parameter. Many extensions can be combined, and they run in declaration order with after-callbacks reversed.

The two I use all the time in Spring projects are SpringExtension, which @SpringBootTest and the test slices register for me and which loads the cached context, injects beans and manages test transactions, and MockitoExtension, which creates @Mock fields, injects @InjectMocks and checks for unused stubs.

About this answer

Last updated
12 November 2026
Versions it names
JUnit 4, JUnit 5
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
JUnit user guide
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "How does the JUnit 5 extension model replace JUnit 4 runners and rules? Give two...": https://scrivio-interview-library.netlify.app/java/junit/4a49635659/