Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 37 ยท Strictness and Extensions

JUnit 5 Extension and Annotations

How @ExtendWith(MockitoExtension.class), @Mock, @InjectMocks, @Spy and @Captor work, how injection picks constructor, setter or field, and the older runner and openMocks options.

Creating every mock with mock(Foo.class) gets repetitive. Mockito's annotations let you declare mocks as fields and have a framework create them and wire them into the object under test. This lesson explains the pieces: the JUnit 5 extension, the annotations, and the rules @InjectMocks uses. You will also run a stand-in that performs the same reflection work, so the "magic" becomes ordinary Java.

Mockito and JUnit are not available on this site. Real code is read-only; the stand-in is labelled.

The extension

Add the artifact org.mockito:mockito-junit-jupiter and annotate the test class:

Java
@ExtendWith(MockitoExtension.class)
class CheckoutServiceTest {

    @Mock PaymentGateway gateway;
    @Mock OrderRepository orders;
    @Spy  PriceCalculator calculator = new PriceCalculator();
    @Captor ArgumentCaptor<Order> orderCaptor;

    @InjectMocks CheckoutService service;

    @Test
    void savesPaidOrder() {
        when(gateway.charge(any())).thenReturn(true);

        service.checkout(new Cart("book"));

        verify(orders).save(orderCaptor.capture());
        assertEquals("PAID", orderCaptor.getValue().status());
    }
}

What the extension does for each test method:

  1. Before the test: creates a fresh mock for every @Mock, @Spy and @Captor field, then builds @InjectMocks objects.
  2. During the test: nothing special; you stub and verify as usual.
  3. After the test: checks strictness (unused stubs fail the test, see Strict stubs) and cleans up.

A new instance of the test class and new mocks are created per test method, so tests do not share state.

The annotations

Annotation Creates
@Mock A mock of the field's type
@Spy A spy; the field may be initialized, or Mockito builds it from a no-argument constructor
@Captor An ArgumentCaptor<T> for the generic type
@InjectMocks The class under test, built from the mocks and spies of the test class

How @InjectMocks chooses

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

  1. Constructor injection. It picks the constructor with the most parameters and passes mocks matched by type. For a parameter type with no matching mock it passes null, so a missing mock can lead to a late NullPointerException.
  2. Property (setter) injection. If the class has a no-argument constructor, it uses setters; matching is by type, then by name if there is more than one candidate.
  3. Field injection. Fields are set directly, again by type then name.

Two practical consequences. If constructor injection is used and the constructor does not take a dependency, no fallback to fields happens for it. And two mocks of the same type are told apart by field name: name the test fields like the constructor parameters or use constructor injection with different types.

What the extension does, in plain Java (stand-in)

The block below defines three tiny annotations and a method Ext.init(testInstance). It finds annotated fields, builds proxies, then picks the largest constructor of the @InjectMocks field. This is the idea behind the real extension, simplified.

Java Reflection behind @Mock and @InjectMocks

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.

Both runs print PAID, and the two gateway identity hashes differ: every test method gets fresh mocks and a fresh service, which is why test order never matters.

Older and alternative ways to initialize

You will meet these in existing code:

Java
// JUnit 4
@RunWith(MockitoJUnitRunner.class)      // JUnit 4 runner, strict by default (MockitoJUnitRunner.Silent is the lenient one)

// No extension: manual initialization
class PlainTest {
    private AutoCloseable mocks;

    @BeforeEach void open()  { mocks = MockitoAnnotations.openMocks(this); }
    @AfterEach  void close() throws Exception { mocks.close(); }
}

openMocks(this) creates the annotated fields but gives no strictness checks, which is another reason to prefer the extension. MockitoAnnotations.initMocks is the old, removed name.

Good habits

  • Prefer constructor injection in production code. Then @InjectMocks has an obvious, compile-checked path, and you can also call the constructor yourself in the test with no annotations at all.
  • Do not put @InjectMocks on an interface or an object that needs logic to be created; build it manually in @BeforeEach.
  • Do not mix annotations and mock(...) calls for the same dependency.
  • Keep mock fields private or package-private; tests do not need public ones.

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. Which artifact provides MockitoExtension for JUnit 5?

    The extension lives in org.mockito:mockito-junit-jupiter, next to mockito-core.
  2. 2. In what order does @InjectMocks try to inject?

    Constructor injection with the biggest constructor is tried first, then setters, then fields.
  3. 3. Do two test methods in one class share the same @Mock instances under MockitoExtension?

    The test class is instantiated per method and mocks are rebuilt, so tests stay independent.

Summary

  • @ExtendWith(MockitoExtension.class) initializes @Mock, @Spy, @Captor and @InjectMocks before each test and checks strictness after it.
  • @InjectMocks uses constructor, then setter, then field injection, matching by type and then by name.
  • Without the extension use MockitoAnnotations.openMocks(this) and close the result; you lose strictness.
  • Constructor injection in production code keeps tests simple and annotation-free if needed.

Next: Mock settings and default answers