Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 37 ยท Mocks and Stubs

InjectMocks and the Mock Annotations

Learn how @InjectMocks builds the class under test: constructor, setter and field injection, matching by type and name, and when to construct by hand instead.

@InjectMocks is the annotation that causes the most confusion in Mockito. It looks like magic: you declare a field of the class under test, and it turns up fully wired with your mocks. When it works it saves lines; when it does not, you get a NullPointerException in the middle of a test and no hint why. This lesson explains the exact rules, shows a stand-in that follows them, and gives you advice on when to avoid the annotation altogether.

Real Mockito code is read-only. The runnable examples use the Mini stand-in from What Is Mockito? plus a small reflection-based injector written for this lesson. It follows the same ideas as Mockito's injection (by type, then by name) but is a simplified model, not Mockito's code.

What the annotations do

In a test class that uses @ExtendWith(MockitoExtension.class) (see Mockito with JUnit and Annotations):

Java
@ExtendWith(MockitoExtension.class)
class OrderServiceTest {

    @Mock PaymentGateway gateway;          // a new mock before each test
    @Mock OrderRepository orders;
    @Spy  PriceFormatter formatter = new PriceFormatter();   // a spy around a real object

    @InjectMocks OrderService service;     // the object under test, built by Mockito
}
  • @Mock creates a mock. Useful options: @Mock(name = "backup") sets the name, @Mock(answer = Answers.RETURNS_DEEP_STUBS) sets the default answer, @Mock(lenient = true) switches off strict-stub checks for that mock.
  • @Spy wraps a real object so real methods run unless stubbed (the Spies chapter covers this).
  • @InjectMocks creates the object (if the field is null) and injects the mocks and spies of the test class into it.
  • @Captor makes an ArgumentCaptor (see ArgumentCaptor).

How @InjectMocks injects

Mockito tries three strategies, in this order, and stops at the first one that applies:

  1. Constructor injection. Mockito picks the biggest constructor (most parameters) and calls it with mocks of matching types. A parameter for which no mock exists receives null. If constructor injection is used, Mockito does not try setters or fields afterwards.
  2. Property (setter) injection. If there is no suitable constructor or the class has only a no-argument constructor, Mockito calls the no-argument constructor and then looks for setter methods whose parameter type matches a mock.
  3. Field injection. If no setter fits, Mockito sets matching fields directly by reflection, even private ones.

When several mocks have the same type, Mockito disambiguates by name: it compares the field or parameter name with the mock's name (the field name in the test class). Everything is silent: if a dependency cannot be resolved, Mockito does not complain, it leaves the field as null. That silent failure is why @InjectMocks is often called a source of confusing NPEs.

Try it: a tiny injector

The program below implements strategy 3 (field injection by type, then by name) with plain reflection so you can see the logic. service is created with the no-argument constructor, and its fields are filled from a list of named mocks:

Java Field injection by type, then by name

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

With one mock per type, Mockito needs only the type. With two Mailer mocks, the field names primaryMailer and backupMailer do the work, which is why real tests often name @Mock fields to match the production class's field names.

Constructor injection and the null trap

Most modern code uses constructor injection:

Java
public class OrderService {
    private final PaymentGateway gateway;
    private final OrderRepository orders;

    public OrderService(PaymentGateway gateway, OrderRepository orders) {
        this.gateway = Objects.requireNonNull(gateway);
        this.orders = Objects.requireNonNull(orders);
    }
}

@InjectMocks OrderService service; picks that constructor and passes the two @Mock fields. If you forgot one @Mock field in the test, Mockito passes null for that parameter, so the requireNonNull above fails with a clear message. Without such a check you get an NPE later. The next program shows the null trap with a hand-rolled constructor injector:

Java Constructor injection and a missing mock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Advice: when not to use @InjectMocks

@InjectMocks shines in small test classes. It becomes a liability when:

  • the class has several constructors or parameters of the same type, so you cannot tell which mock goes where;
  • a dependency is missing from the test and fails silently as null;
  • the class takes primitives, strings or configuration values in its constructor (Mockito cannot invent them, so they become 0, null or false);
  • you want the compiler to notice when a constructor gains a parameter.

The explicit alternative costs one line and has none of these problems:

Java
@BeforeEach
void setUp() {
    service = new OrderService(gateway, orders);
}

Many teams use this form everywhere. It is also friendlier to readers who have never heard of @InjectMocks.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In which order does @InjectMocks try to inject?

    Mockito tries the biggest constructor first, then setters, then fields, and stops at the first strategy that applies.
  2. 2. What happens when no mock matches a constructor parameter?

    Mockito injects null silently, which is why missing dependencies often show up as NullPointerExceptions.
  3. 3. Two @Mock fields have the same type. How does field injection choose between them?

    When types are ambiguous, Mockito falls back to matching by name.
  4. 4. Which alternative to @InjectMocks gives compile-time safety when a constructor changes?

    An explicit new OrderService(gateway, orders) fails to compile if the constructor signature changes, so the test cannot silently use null.

Summary

  • @Mock creates mocks, @Spy wraps real objects, @Captor makes captors, and @InjectMocks builds the class under test.
  • Injection order: constructor (biggest), setters, fields; mocks are matched by type, then by name.
  • Unresolved dependencies become null silently, which causes confusing NPEs.
  • Constructing the class yourself in @BeforeEach is explicit, compiler-checked and often the better choice.

Next: Verification Basics