Mockito JUnit 5 Extension Setup With MockitoExtension
Set up Mockito with JUnit 5 using MockitoExtension, Mock, InjectMocks and Captor, choose strictness, and avoid manual MockitoAnnotations.openMocks calls.

JUnit 5 has an extension model, and Mockito plugs into it with one annotation. Before that, Mockito tests started with MockitoAnnotations.openMocks(this) in a @BeforeEach, or with a JUnit 4 runner that does not exist in Jupiter. This post covers the setup, what the extension does around each test, how @InjectMocks picks a constructor, and the strictness setting that decides whether a sloppy test fails. It applies to Mockito 5 with JUnit 5 or 6.
The dependency
mockito-junit-jupiter is a separate artifact from mockito-core. It holds the extension and nothing else.
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>5.14.2</version>
<scope>test</scope>
</dependency>If the project uses spring-boot-starter-test, the artifact is already on the classpath and the version comes from the Boot BOM, so declare it without a version. In Gradle it is testImplementation("org.mockito:mockito-junit-jupiter"). Mockito 5 uses the inline mock maker by default, which needs a Java agent on newer JDKs; the warning that produces is explained in the inline agent warning.
What one annotation does
@ExtendWith(MockitoExtension.class)
class ShippingServiceTest {
@Mock CarrierClient carrier;
@Mock AddressValidator validator;
@InjectMocks ShippingService service;
@Test
void books_a_pickup_for_a_valid_address() {
when(validator.isValid(any())).thenReturn(true);
when(carrier.book(any())).thenReturn(new Booking("b-1"));
Booking booking = service.schedule(new Parcel("12 High St"));
assertEquals("b-1", booking.id());
verify(carrier).book(any());
}
}Before each test method, the extension creates a new mock for every @Mock field and a new spy for every @Spy field, then builds the @InjectMocks object from them. After each test it checks the stubbing you did. There is no @BeforeEach, no openMocks() and no @AfterEach to close the mocks. Because the objects are rebuilt for every test, no state leaks from one test to the next, which removes a whole class of order-dependent failures. A test that passes alone and fails in the suite is rarely a Mockito problem once this is in place.
The annotation list is short. @Mock creates a mock, @Spy wraps a real object, @Captor creates an ArgumentCaptor<T> with its generic type intact, and @InjectMocks builds the class under test.
How @InjectMocks chooses
Mockito tries three strategies in a fixed order and stops at the first that works. It tries constructor injection with the biggest constructor, then setter injection, then field injection. It matches mocks to parameters by type, and by name when two mocks share a type.
The failure mode is quiet. If a constructor parameter has no matching mock, Mockito passes null for it and carries on. The test then fails later with a NullPointerException inside the code under test, which looks like a bug in production code. Two defences help. Declare a mock for every collaborator, or build the object yourself:
@BeforeEach
void setUp() {
service = new ShippingService(carrier, validator);
}Explicit construction is a line longer and fails at compile time when the constructor changes. For classes with more than two collaborators, prefer it. @InjectMocks earns its place on small classes where the wiring is obvious.
Mocks as method parameters
The extension also resolves parameters, so a mock can be scoped to a single test.
@Test
void rejects_an_invalid_address(@Mock AddressValidator validator) {
when(validator.isValid(any())).thenReturn(false);
var service = new ShippingService(mock(CarrierClient.class), validator);
assertThrows(InvalidAddressException.class, () -> service.schedule(new Parcel("???")));
}This is useful when only one test needs a given collaborator, and it keeps the class free of fields that most tests ignore. It combines with @ParameterizedTest, where the mock parameter has to come after the arguments the source provides.
Strictness is the default and it is useful
The extension runs with strict stubs. Two things follow.
An unused stub fails the test with UnnecessaryStubbingException. If you stub validator.isValid(...) and the code path never calls it, the stub is dead, and the test is telling you the setup describes something that no longer happens.
A stubbed method called with different arguments raises PotentialStubbingProblem. That catches the case where the stub says get("a") and the code calls get("b"), which would otherwise return null and produce a confusing failure three lines later. The details of both are in strict stubs, and the fix for the first error is in UnnecessaryStubbingException.
To relax it for a class:
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class LegacyShippingTest { /* ... */ }Treat lenient as a stopgap for a legacy suite you are migrating. When one shared @BeforeEach stubs things only some tests use, move the stub into the tests that need it, or use lenient().when(...) for that single stub rather than relaxing the whole class.
Using it next to Spring
In a Spring test the mocks have to live in the application context, and the extension does not put them there. Use @MockitoBean for that, as shown in MockitoBean. A plain unit test with no context uses @ExtendWith(MockitoExtension.class) and runs in milliseconds. The practical rule: if the test needs @Autowired, it is a Spring test; if it only needs new, it is a Mockito test. Mixing both annotations on one class gives two sets of mocks and a confusing failure when they disagree.
@Nested classes work too. Each nested class gets its own mocks, rebuilt per test, and the outer class fields are visible inside it.
Calling Mockito by hand
Mockito.mock() called inside a test is not managed by the extension. It still works, but it is not checked for strictness and it is not reset. If you want strictness for hand-made mocks, open a MockitoSession with Mockito.mockitoSession().initMocks(this).strictness(Strictness.STRICT_STUBS).startMocking() and call finishMocking() at the end. Most suites never need it.
Captors and spies under the same extension
A field annotated @Captor ArgumentCaptor<Booking> booking; is created for each test as well, so verify(carrier).book(booking.capture()) works without ArgumentCaptor.forClass. Spies follow the same lifecycle. A @Spy field that is already initialised, such as @Spy List<String> log = new ArrayList<>();, is wrapped as given, which is the clean way to observe a real collaborator without mocking all of it. Because the spy is rebuilt per test, its recorded interactions never carry over.
JUnit 4 projects
The extension is a JUnit 5 mechanism. A JUnit 4 class keeps @RunWith(MockitoJUnitRunner.class) or the MockitoRule, and the vintage engine runs it. If the project is in the middle of a migration, both styles can coexist in the same module, as long as the vintage engine is on the test classpath.
The basics of stubbing and verifying are in the Mockito tutorial. The reference for the extension is the [MockitoExtension Javadoc](https://javadoc.io/doc/org.mockito/mockito-junit-jupiter/latest/org/mockito/junit/jupiter/MockitoExtension.html), and the JUnit user guide on extensions explains the model it plugs into.


