Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Rewrite this test setup with Mockito annotations and the JUnit 5 extension, and explain what each annotation does:

Java
OrderRepository repo = mock(OrderRepository.class);
EmailSender email = mock(EmailSender.class);
OrderService service = new OrderService(repo, email);
ArgumentCaptor<Email> captor = ArgumentCaptor.forClass(Email.class);

We put @ExtendWith(MockitoExtension.class) on the test class, declare @Mock OrderRepository repo and @Mock EmailSender email, @InjectMocks OrderService service, and @Captor ArgumentCaptor<Email> captor. The extension creates all of them fresh before each test and checks strict stubbing after it. @InjectMocks builds the service, trying constructor injection first, then setters, then fields, and @Captor avoids the unchecked generic cast; @Spy, for completeness, wraps a real object.

Why this question is asked

Almost every Spring project has test classes that start with a block of @Mock fields. The annotations save some typing, but they also hide decisions, such as how the object under test gets its dependencies, and that is where subtle bugs start. Interviewers ask this question to check that we know what each annotation does rather than copying it. In this answer, we will rewrite the manual setup with annotations, go through each annotation and what happens behind it, look at how @InjectMocks chooses an injection strategy, cover the strict stubs check the extension adds, and discuss when the explicit constructor is still the better choice.

1The Manual Setup We Start From

Here is the setup from the question, placed in a JUnit 5 test. Nothing here is wrong: each line creates exactly what it says, and anyone can read it without knowing Mockito's annotations.

Java
class OrderServiceTest {
OrderRepository repo = mock(OrderRepository.class);
EmailSender email = mock(EmailSender.class);
OrderService service = new OrderService(repo, email);
@SuppressWarnings("unchecked")
ArgumentCaptor<Email> captor = ArgumentCaptor.forClass(Email.class);
}

Notice that JUnit 5 creates a new instance of the test class for every test method by default, so these field initialisers already give each test fresh mocks. The annotation version keeps that property, and adds a few things, as we will see.

2The Same Setup With Annotations

Now the rewrite. The class gets the Mockito extension, and each field gets the annotation that describes its role.

Java
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.*;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
@Mock OrderRepository repo; // a mock, created before each test
@Mock EmailSender email; // a second mock
@InjectMocks OrderService service; // built with repo and email
@Captor ArgumentCaptor<Email> captor; // typed captor, no unchecked cast
@Test
void sendsConfirmation() {
when(repo.save(any())).thenAnswer(inv -> inv.getArgument(0));
service.place(new Order("a@b.com"));
verify(email).send(captor.capture());
assertEquals("a@b.com", captor.getValue().to()); // passes
}
}
Step throughWhat MockitoExtension does around each test
JUnitMockitoExtensionTest instance
beforeEach
create @Mock and @Captor fields
build @InjectMocks field with the mocks
run the test method
afterEach
check strict stubs, report unused stubs

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

The fields have no initialisers, so something must fill them. That is the extension's job: before each test it scans the instance for these annotations and creates the objects, and after each test it runs Mockito's checks.

3What Each Annotation Does

@ExtendWith(MockitoExtension.class) registers Mockito with JUnit 5. It initialises the annotated fields before each test, starts a Mockito session with strict stubs, and finishes the session after the test, which is when usage problems are reported.

@Mock creates a mock of the field's type, exactly like mock(OrderRepository.class). The mock records calls and returns default values (null, 0, false, empty collections and Optional.empty()) until we stub it.

@InjectMocks creates a real instance of the field's type, here OrderService, and injects the mocks declared in the test into it. It is the only annotation that builds a real object, which is why it deserves the most attention.

@Captor creates an ArgumentCaptor whose type comes from the field declaration. Because Mockito reads the full generic type, ArgumentCaptor<List<Email>> works without the unchecked cast that ArgumentCaptor.forClass() forces for generic types.

@Spy, which our setup does not need, wraps a real object: calls go to the real methods unless we stub them, and we can still verify them. It is useful for partially faking a real object, but it is easy to overuse, and stubbing a spy should use doReturn(...).when(spy) so the real method is not called during stubbing.

4How @InjectMocks Chooses an Injection Strategy

@InjectMocks tries three strategies in order. First, constructor injection: it picks the biggest constructor and resolves each parameter by type from the declared mocks; a parameter with no matching mock receives null. If that constructor succeeds, Mockito stops there and does not try anything else. Second, if there is only a no-argument constructor, it uses setter injection, matching mocks to setters by type and then by name. Third, field injection, again by type and then by name.

There is a catch: none of these strategies reports a failure. If a dependency cannot be matched, the field or parameter simply stays null, and we only find out when the test throws a NullPointerException inside the service. So the clearest design for the class under test is a single constructor that takes every dependency. Then @InjectMocks has only one possible path, and it is the same path Spring uses in production.

Step throughHow @InjectMocks builds the object
  1. Constructor with arguments?
    YesUse the biggest one, match mocks by typeNoUse the no-argument constructor
  2. Constructor injection succeeded?
    YesStop: no setter or field injectionNoTry setters, then fields
  3. Every dependency matched?
    YesObject readyNoUnmatched ones stay null, no error

3 steps in order. Play them, or step through them one at a time.

5Explicit Constructor or @InjectMocks?

Many experienced teams use @Mock and @Captor but still call the constructor themselves. The reason is clarity and safety. When we write new OrderService(repo, email) in a @BeforeEach, the compiler checks that the arguments match, a new constructor parameter breaks the test at compile time instead of silently becoming null, and readers see the wiring at a glance.

Java
@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
@Mock OrderRepository repo;
@Mock EmailSender email;
@Captor ArgumentCaptor<Email> captor;
OrderService service;
@BeforeEach
void setUp() { service = new OrderService(repo, email); } // the compiler checks the wiring
}

Both styles are fine for a class with a single constructor and dependencies of distinct types. I would choose the explicit constructor as soon as there are two dependencies of the same type, or more than one constructor.

6Follow-up questions

What does MockitoExtension's strict stubs mode report?

It reports two things. After the test, any stub created with when() that the test never used fails the test with UnnecessaryStubbingException, naming the line. During the test, if the code calls a stubbed method with different arguments from the stub, Mockito throws PotentialStubbingProblem at that call, showing both argument lists. Individual stubs can be relaxed with lenient().

Do I need MockitoAnnotations.openMocks(this) with the extension?

No. openMocks() is the manual way to initialise annotated fields, used without the extension, and it returns an AutoCloseable that must be closed after the test. The extension does both for us.

Can @InjectMocks inject into a Spring bean?

No. It has nothing to do with the Spring context; it simply creates a plain object. Replacing beans in a Spring test context is done with @MockitoBean, which is a different mechanism.

7Conclusion

In this answer, we rewrote a manual Mockito setup with @ExtendWith(MockitoExtension.class), @Mock, @InjectMocks and @Captor. The extension creates the fields before each test and checks strict stubbing after it, @Mock creates mocks, @InjectMocks builds the real object by constructor, then setter, then field injection without reporting failures, @Captor gives a typed captor without an unchecked cast, and @Spy wraps a real object. With constructor injection, @InjectMocks is predictable, but calling the constructor explicitly is often clearer.

What to say in the interviewAbout 70 seconds aloud

Open with

I would annotate the class with @ExtendWith(MockitoExtension.class), declare @Mock OrderRepository repo and @Mock EmailSender email, @InjectMocks OrderService service, and @Captor ArgumentCaptor<Email> captor. The extension creates fresh objects for these fields before every test, and after each test it finishes a Mockito session with strict stubs, which fails the test on stubs that were never used and reports argument mismatches when a stubbed method is called with different arguments. @Mock is the same as calling mock. @InjectMocks builds a real OrderService and injects the declared mocks: it tries the biggest constructor first, matching by type, and if that works it stops; otherwise it tries setters and then fields, by type and then by name.

Then, if they want more

It never reports a failure, so anything it cannot match stays null. @Captor reads the generic type from the field, so I avoid the unchecked cast that forClass needs, and @Spy, if I needed it, wraps a real object. Because the class uses constructor injection, @InjectMocks is predictable here.

Still, many teams, including me, often keep @Mock but call new OrderService(repo, email) in a BeforeEach, because the compiler then checks the wiring.

About this answer

Last updated
12 November 2026
Versions it names
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.
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 "Rewrite this test setup with Mockito annotations and the JUnit 5 extension, and explain...": https://scrivio-interview-library.netlify.app/java/mocking/db3e1a2155/