Scrivio Interview library
DebuggingIntermediate7 min read · updated 12 November 2026

A test uses @InjectMocks PaymentService service with two @Mock fields of the same type, PaymentGateway primary and PaymentGateway fallback. The test passes, but the service calls the wrong gateway, and another test shows a mock as null inside the service. Explain how @InjectMocks chooses and fails, and how you would fix the tests.

@InjectMocks matches mocks to dependencies mainly by type, so with two PaymentGateway mocks it has to guess which goes where, and depending on the strategy and the names it can put them in the wrong places or inject none. It never reports this: if constructor injection succeeds, it stops even if a parameter got null, and if it falls back to field injection and cannot decide, the field stays null. The fix is to construct PaymentService explicitly in a @BeforeEach, passing primary and fallback in the right order.

Why this question is asked

This is a nasty kind of test bug, because one test passes for the wrong reason and another fails in a confusing place. Interviewers ask it at the ten-year level because finding the cause requires knowing how @InjectMocks actually works, and fixing it well requires the judgement to remove the magic rather than add more. In this answer, we will set up the failing tests, walk through how @InjectMocks matches mocks in each strategy, see exactly where the wrong gateway and the null come from, fix the tests, and finish by contrasting @InjectMocks with @MockitoBean in Spring Boot tests.

1The Setup That Misbehaves

PaymentService takes two gateways of the same type: it charges through the primary one and switches to the fallback if the primary fails. It also takes a FraudCheck. The test declares two gateway mocks with names that look obvious to a human, and forgets the FraudCheck.

Java
public class PaymentService {
private final PaymentGateway primaryGateway;
private final PaymentGateway fallbackGateway;
private final FraudCheck fraud;
public PaymentService(PaymentGateway primaryGateway, PaymentGateway fallbackGateway, FraudCheck fraud) { ... }
}
@ExtendWith(MockitoExtension.class)
class PaymentServiceTest {
@Mock PaymentGateway primary;
@Mock PaymentGateway fallback;
@InjectMocks PaymentService service;
@Test
void usesFallbackWhenPrimaryFails() {
when(primary.charge(any())).thenThrow(new GatewayDown());
service.pay(order);
verify(fallback).charge(any()); // can pass or fail for reasons unrelated to the code
}
}

To a reader, primary clearly belongs in primaryGateway. But Mockito does not read intentions. It sees two parameters of type PaymentGateway and two mocks of type PaymentGateway, and it has to match them by rules that were never designed for this case.

2How Constructor Injection Matches Mocks

With a constructor that takes arguments, @InjectMocks uses the biggest constructor and resolves each parameter from the declared mocks by type. When several mocks share the type, which one each parameter gets is not something the test controls. Parameter names are only available at runtime if the code is compiled with the -parameters flag, and even then we should not rely on Mockito using them; check your version. In practice the two gateways can end up swapped, or the same mock can be passed twice.

Now look at what that does to our test. If both parameters receive the same mock, the 'primary' stub throws for both calls, but whether verify(fallback) passes depends on which mock was used. If they are swapped, the service charges fallback first. The test may pass while the service, in this wiring, is calling the wrong gateway, which is exactly the symptom in the question.

There is one more rule: if a constructor parameter has no matching mock at all, Mockito passes null and still considers constructor injection a success. Because it succeeded, Mockito does not try setter or field injection afterwards. Our test declares no FraudCheck mock, so the service is created with null in that slot, and as soon as pay() calls fraud.allows(), the test crashes inside the service with a NullPointerException.

How each strategy matches PaymentGateway mocks
StrategyRuleWhat can go wrong here
Constructor (biggest)resolve parameters by typesame-type mocks swapped or duplicated
Constructor, missing mockpass null, still a successnull dependency, no error
Setter or fieldby type, then by field namenames differ, so nothing injected
Any strategyfailures are not reportedfound only at runtime

3How Field Injection Leaves a Mock Null

Now suppose another test class uses an older version of PaymentService with a no-argument constructor and @Autowired fields. @InjectMocks then uses field injection: for each field it looks for mocks of the same type; if exactly one matches, it is injected regardless of the name; if several match, it picks the one whose mock name equals the field name.

Our mocks are called primary and fallback, while the fields are called primaryGateway and fallbackGateway. Two candidates, no name match, so Mockito cannot decide and injects nothing into those fields. They stay null, the test runs, and the service throws a NullPointerException on its first charge. That is the second symptom in the question: a mock is null inside the service, with no hint from Mockito about why.

Java
// Field injection case: names do not match, so neither gateway is injected
@Mock PaymentGateway primary; // field in service: primaryGateway
@Mock PaymentGateway fallback; // field in service: fallbackGateway
@InjectMocks PaymentServiceWithFields service;
service.pay(order); // NullPointerException: primaryGateway is null
// Renaming the mocks to the field names would make it work, but silently, and only until a rename

The silence is the real problem. Every one of these outcomes is legal from @InjectMocks' point of view, so the test framework gives no signal, and we debug a null or a wrong call as if the production code were broken.

4The Fix: Construct the Service Explicitly

The robust fix is to stop asking Mockito to guess. We keep @Mock for creating the mocks, and we call the constructor ourselves, in the order the constructor defines. The compiler now checks the number and types of arguments, and the reader sees which mock goes where.

Java
@ExtendWith(MockitoExtension.class)
class PaymentServiceTest {
@Mock PaymentGateway primary;
@Mock PaymentGateway fallback;
@Mock FraudCheck fraud;
PaymentService service;
@BeforeEach
void setUp() {
service = new PaymentService(primary, fallback, fraud); // explicit, compiler-checked order
}
@Test
void usesFallbackWhenPrimaryFails() {
when(fraud.allows(any())).thenReturn(true);
when(primary.charge(any())).thenThrow(new GatewayDown());
service.pay(order);
verify(primary).charge(any()); // passes: tried first
verify(fallback).charge(any()); // passes: then the fallback
}
}

Notice that we now also verify that the primary was tried first, which proves the wiring is what we think. If the class has a new dependency tomorrow, this test stops compiling, which is far better than a null at runtime. If we must keep @InjectMocks, the weaker alternative is to name mocks exactly like the fields or parameters and compile with -parameters, but that couples the test to private names and still fails silently when someone renames one.

5@InjectMocks Versus @MockitoBean in Spring Boot

It is easy to confuse @InjectMocks with Spring's test annotations, but they work at different levels. @InjectMocks builds one plain object outside any Spring context. @MockitoBean, introduced in Spring Framework 6.2 to replace Spring Boot's @MockBean (deprecated since Boot 3.4 and removed in Boot 4; check your version), replaces a bean inside the Spring application context with a Mockito mock, so every bean that depends on it receives the mock through Spring's own injection.

In a Spring test with two PaymentGateway beans, Spring resolves them as it does in production, by qualifier or bean name, and @MockitoBean can target a specific bean by name. That avoids the ambiguity problem, but at the cost of starting a context, which is slow, and every distinct set of @MockitoBean overrides creates another cached context. So for a unit test of PaymentService the explicit constructor remains the best choice; @MockitoBean belongs in slice or integration tests.

@InjectMocks compared with @MockitoBean
Aspect@InjectMocks@MockitoBean
Works onone plain objecta bean in the Spring context
Injection rulesMockito: type, then nameSpring: type, qualifier, bean name
Failure when ambiguoussilent null or wrong mockstartup error, or choose by name
Costmillisecondsa Spring context, cached per configuration

6Follow-up questions

Why does constructor injection not fall back to field injection after passing null?

Because Mockito treats a successfully created object as the end of injection. It cannot know that a null was not intended, so it does not try other strategies, and it does not report anything.

Could a qualifier annotation help @InjectMocks?

No. Mockito does not read Spring's @Qualifier. Only the name of the mock (the field name or the name attribute of @Mock) and the type are used.

Is there a way to make Mockito fail on unresolved injection?

Not reliably through @InjectMocks. The dependable way to get a failure is the compiler, by calling the constructor directly.

7Conclusion

In this answer, we saw that @InjectMocks matches mocks mainly by type, so two PaymentGateway mocks can be swapped or duplicated by constructor injection, and that field injection falls back to names and injects nothing when the names differ. Constructor injection passes null for unmatched parameters and stops there, and no strategy reports a failure. The fix is to construct the service explicitly in a @BeforeEach with the mocks in the right order, while @MockitoBean is a separate mechanism that replaces beans in a Spring context.

What to say in the interviewAbout 80 seconds aloud

Open with

@InjectMocks matches by type first, and two mocks of the same type defeat it. With a constructor, it uses the biggest one and resolves parameters by type, so with two PaymentGateway mocks it can swap them or pass the same one twice, which is how a test can pass while the service is wired to the wrong gateway.

Then, if they want more

If a parameter has no mock at all, Mockito passes null and still considers constructor injection successful, so it does not try anything else. With field or setter injection it matches by type and then by name, and since my mocks are called primary and fallback while the fields are primaryGateway and fallbackGateway, it cannot decide and leaves both null.

None of this is reported, so I see a NullPointerException or a wrong call and think the code is broken. My fix is to keep @Mock but construct the service myself in a BeforeEach, new PaymentService(primary, fallback, fraud), so the compiler checks the wiring, and to verify that primary was called before fallback.

Renaming mocks to match fields works but is fragile. And I would not confuse this with @MockitoBean, which replaces the deprecated @MockBean and replaces beans in a Spring context using Spring's own rules, at the cost of a context.

About this answer

Last updated
12 November 2026
Versions it names
Spring Framework 6
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 "A test uses @InjectMocks PaymentService service with two @Mock fields of the same type...": https://scrivio-interview-library.netlify.app/java/mocking/4b9d63e23d/