Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 37 ยท Getting Started

Mockito with JUnit and Annotations

Use @ExtendWith(MockitoExtension.class), @Mock and @InjectMocks with JUnit Jupiter, learn how fields are initialised per test, and when to skip annotations.

Calling mock(...) inside every test works, but test classes with several mocks quickly fill up with boilerplate. Mockito offers annotations that declare mocks as fields and a JUnit extension that creates them for you before each test. This lesson shows the standard JUnit Jupiter setup (JUnit 5 and JUnit 6 behave the same here), what the extension does for you, and how to do the same thing without it.

Real Mockito and JUnit code is shown read-only. The runnable examples rebuild the idea of the extension with a tiny reflection helper on top of the Mini stand-in (see What Is Mockito?).

The standard setup

Here is a complete real test class, using the SignupService from the first lesson. Read it top to bottom:

Java
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
class SignupServiceTest {

    @Mock UserRepository users;          // a fresh mock before every test
    @Mock Mailer mailer;

    @InjectMocks SignupService service;  // built with the mocks above

    @Test
    void newUserGetsAWelcomeMail() {
        when(users.existsByEmail("[email protected]")).thenReturn(false);

        boolean registered = service.register("[email protected]");

        assertTrue(registered);
        verify(users).save("[email protected]");
        verify(mailer).send("[email protected]", "Welcome!");
    }

    @Test
    void existingUserIsRejected() {
        when(users.existsByEmail("[email protected]")).thenReturn(true);

        assertFalse(service.register("[email protected]"));
        verify(users, never()).save(anyString());
    }
}

Four pieces cooperate:

  • @ExtendWith(MockitoExtension.class) hooks Mockito into JUnit's lifecycle. Before each test method it inspects the test instance and initialises annotated fields.
  • @Mock marks a field to be filled with a fresh mock(Type.class).
  • @InjectMocks builds the class under test and injects the mocks into it (the rules are covered in InjectMocks and Mock Annotations).
  • The extension also turns on strict stubs: unused stubbings and mismatching calls are reported. Strictness has its own chapter later in the course; for now know that if you stub something the test never uses, a strict run fails with UnnecessaryStubbingException.

Mocks are fresh for every test

JUnit creates a new instance of the test class for every test method, and the extension fills the @Mock fields of that new instance. So no stubbing or recorded call leaks from one test into the next, and test order does not matter. This is one of the biggest reasons to use annotations: you cannot accidentally forget to reset a shared mock.

The stand-in below mimics that behavior. A custom @Mock annotation and a small initMocks method scan the fields of a test object by reflection; a mini runner creates a new test object for each test method. It is not Mockito's code, but the shape is the same:

Java What the extension does, in plain Java

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.

The method order printed depends on reflection, but whichever test runs second prints false: its mock is brand new.

@Captor, @Spy and friends

Mockito has a few more annotations. They are explained in their own lessons, so here is only the map:

Annotation What it creates Covered in
@Mock A mock of the field's type This chapter
@InjectMocks The class under test, wired with the mocks InjectMocks and Mock Annotations
@Captor An ArgumentCaptor for the generic type ArgumentCaptor
@Spy A spy that wraps a real object Spies and Partial Mocks chapter

Without the extension

You do not have to use the extension. Two alternatives exist:

1. Call mock(...) yourself, as in the examples so far. Use it when a test needs only one mock or when you want the mock created inside a helper method:

Java
class SignupServiceTest {
    UserRepository users = mock(UserRepository.class);
    Mailer mailer = mock(Mailer.class);
    SignupService service = new SignupService(users, mailer);   // plain constructor call
}

Because JUnit builds a new test instance per method, these field initialisers also give you fresh mocks for each test. Many developers prefer this style: it is explicit, needs no extension, and constructing the class under test by hand makes constructor changes show up as compile errors.

2. Use MockitoAnnotations.openMocks(this) in a @BeforeEach method (older code uses the removed initMocks). It returns an AutoCloseable that releases resources, so close it in @AfterEach:

Java
class LegacyStyleTest {
    @Mock UserRepository users;
    private AutoCloseable closeable;

    @BeforeEach
    void setUp() {
        closeable = MockitoAnnotations.openMocks(this);
    }

    @AfterEach
    void tearDown() throws Exception {
        closeable.close();
    }
}

This route does not enable strict stubs. The extension is the better default for JUnit 5 and 6, and MockitoJUnitRunner (@RunWith) is its JUnit 4 equivalent.

Per-test mocks inside the test

One more pattern: declare the field mocks with @Mock, but create a special-purpose mock for one test with mock(...) locally. Mixing is fine, as the next example shows. It also uses the extension's idea of resetting state: each call to fresh() below is a new test instance.

Java Field mock plus a local 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.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does @ExtendWith(MockitoExtension.class) do before each test method?

    The extension creates the mocks for annotated fields and, in strict mode, checks for unused stubbings afterwards.
  2. 2. Why do stubs from one test not leak into the next one?

    A new test instance means new @Mock fields, which are fresh mocks.
  3. 3. Which approach lets you use @Mock without the JUnit extension?

    openMocks(this) initialises the annotated fields manually. It returns an AutoCloseable you should close.
  4. 4. Which annotation builds the class under test and injects the mocks?

    @InjectMocks creates the instance and passes in the matching mocks.

Summary

  • @ExtendWith(MockitoExtension.class) plus @Mock fields removes mock(...) boilerplate; it also enables strict stubs.
  • @InjectMocks builds the class under test from the mocks; @Captor and @Spy cover captors and spies.
  • JUnit creates a new test instance per method, so mocks are fresh and tests do not influence each other.
  • Without the extension, use mock(...) in field initialisers or MockitoAnnotations.openMocks(this) with close().
  • Constructing the class under test by hand keeps tests explicit and needs no magic.

Next: Stubbing Return Values