Skip to content
Visual explainer 3h to learn 4 steps

Mocking with Mockito

Isolate units with mocks and verify interactions.

By Invicly Tech, , in Backend Java Development. About 10 minutes to read.

Topic 11 of 29

In short

Mockito creates fake versions of dependencies so you can test one class in isolation. You stub what the fake returns and verify how it was called.

Explained simply

Most classes depend on other classes. An OrderService might use a repository, a payment client and an email sender. To unit test OrderService alone, you do not want a real database, a real bank and real emails. You want stand-ins you control.

Mockito creates those stand-ins, called mocks. A mock looks like the real class but does nothing on its own. You tell it what to return for specific calls, which is called stubbing, and afterwards you can ask it what calls it received, which is called verifying.

This lets you test tricky situations easily. What if the payment fails? Make the payment mock throw an exception. What if the user is missing? Make the repository mock return an empty Optional. No setup of real systems is needed.

Mocks are a tool, not a goal. Mock the things at the edge of your class, like other services and outside systems. Do not mock simple data objects, and do not mock so much that the test only proves that mocks call mocks.

Press Play on a diagram to walk through it one step at a time.

SequenceA unit test with a mock
Test
UserService
Mock repository
  1. 1when findById(1) thenReturn Ana
    Test to Mock repository: when findById(1) thenReturn Ana
  2. 2getName(1)
    Test to UserService: getName(1)
  3. 3findById(1)
    UserService to Mock repository: findById(1)
  4. 4stubbed User Ana
    Mock repository to UserService: stubbed User Ana
  5. 5returns Ana
    UserService to Test: returns Ana
  6. 6verify findById(1) called once
    Test to Mock repository: verify findById(1) called once
MapThe family of test doubles
Test double
  • Dummy
    • Passed in but never used
  • Stub
    • Returns preset answers
  • Fake
    • Working shortcut, such as an in-memory store
  • Mock
    • Stubbed and verified, as Mockito does
  • Spy
    • Real object that also records calls

In depth

What a mock really is

Mockito generates a class at run time, using the ByteBuddy library, that extends or instruments your type. Every method on it is intercepted. Since Mockito 5 the inline mock maker is the default, so final classes and final methods can be mocked too. Static methods can be mocked with mockStatic inside a try-with-resources block, but needing it is usually a design smell.

An unstubbed method does not throw; it returns a harmless default. Numbers give 0, booleans false, objects null, and common container types give empty values: an empty List, Set, Map, Optional or Stream. That is convenient, but it also means a forgotten stub can make code quietly take the wrong path, so read failures carefully.

  • Unstubbed: 0, false, null, empty collection, Optional.empty()
  • Mockito 5 needs Java 11 or later
  • On Java 21+, configure Mockito as a -javaagent to avoid dynamic agent warnings

Stubbing and argument matchers

when(repo.findById(1L)).thenReturn(Optional.of(user)) stubs one exact call. thenThrow makes a call fail, thenAnswer computes a reply from the arguments, and chaining thenReturn(a, b) returns a then b on later calls. For void methods and spies use the do-family: doThrow(new MailException()).when(mailer).send(any()).

Matchers like any(), anyString(), eq(5) and argThat(...) match many values. One strict rule: if any argument uses a matcher, all arguments must use matchers. when(repo.find(anyString(), "x")) fails; write eq("x") instead. With MockitoExtension, Mockito uses strict stubs: a stub that the test never uses causes UnnecessaryStubbingException, and a call with different arguments is reported, which keeps tests honest and tidy.

  • thenReturn, thenThrow, thenAnswer
  • doReturn / doThrow / doNothing for void methods and spies
  • All arguments matchers or none

Verifying calls and capturing arguments

verify(mailer).send(any()) checks that a call happened exactly once. You can change the count with times(2), never(), atLeastOnce() or atMost(3). InOrder checks the sequence of calls across one or more mocks, for example that you saved the order before sending the email.

When the important thing is what was passed, use an ArgumentCaptor. Declare @Captor ArgumentCaptor<Email> captor, call verify(mailer).send(captor.capture()), then assert on captor.getValue(). This is cleaner than a complicated argThat matcher and gives readable failures. Verify only interactions that matter to the behaviour, like a payment being charged or an email being sent. Verifying every internal call ties the test to the implementation, and it breaks on harmless refactors.

FlowUsing an ArgumentCaptor
  1. 1
    Declare captor

    @Captor ArgumentCaptor<Email> captor

  2. 2
    Run the code

    service.register("ana@x.com")

  3. 3
    Capture

    verify(mailer).send(captor.capture())

  4. 4
    Read the value

    Email sent = captor.getValue()

  5. 5
    Assert

    Check recipient, subject and body

@InjectMocks and its traps

@InjectMocks creates the class under test and fills its dependencies with your @Mock fields. It tries constructor injection first, using the biggest constructor, then setter injection, then field injection. The trap: if it cannot match a dependency, it does not fail. The field simply stays null, and you get a NullPointerException deep in the test that looks unrelated.

Many teams therefore skip @InjectMocks and build the object themselves in @BeforeEach: service = new OrderService(repo, payments, mailer). It is one extra line, the compiler checks it, and adding a new dependency breaks the test loudly instead of silently. A spy (@Spy or spy(realObject)) wraps a real object and calls real methods unless stubbed; use it sparingly, mostly for legacy code.

When not to mock

Do not mock value objects such as records, DTOs, String or BigDecimal; just create real ones. Do not mock the class under test. Avoid mocking types you do not own, such as an HTTP client, JdbcTemplate or EntityManager: your stubs encode your guess of how they behave, and the guess may be wrong. Wrap them in your own small interface and mock that, or test them for real.

Database code is the classic case. A mocked repository proves nothing about your SQL, mappings or constraints. Use @DataJpaTest with Testcontainers for that layer. Sometimes a fake is better than a mock: a simple in-memory implementation of a repository interface lets you test real behaviour across several calls without any stubbing. Keep mocks for slow, remote or side-effecting collaborators.

CompareMock, fake or the real thing?
Mock
  • Scripted answers per test
  • Can verify calls
  • Good for remote or side effects
  • Tied to how code calls it
Fake
  • Simple working implementation
  • Like an in-memory repository
  • Behaves the same across tests
  • No stubbing needed
Real (Testcontainers)
  • Actual Postgres, Redis, Kafka
  • Catches SQL and mapping bugs
  • Slower: seconds, not milliseconds
  • Best for integration tests

Learn it in 4 short steps

About 45m each. Track them with a timer in your plan.

  1. 1
    Create mocks with @Mock and @InjectMocks~45m
  2. 2
    Stub calls with when and thenReturn~45m
  3. 3
    Verify interactions and capture arguments~45m
  4. 4
    Know when not to mock~45m

Key points

  • @Mock creates a fake; @InjectMocks builds the class under test with those fakes.
  • Stub with when(...).thenReturn(...) and check calls with verify(...).
  • ArgumentCaptor grabs the argument passed to a mock so you can assert on it.
  • Do not mock value objects or the class you are testing; mock its collaborators.

Key terms

Tap a card to flip it. 0/5 known

Examples

java
@ExtendWith(MockitoExtension.class)
class UserServiceTest {
  @Mock UserRepository repo;
  @InjectMocks UserService service;

  @Test
  void returnsUserName() {
    when(repo.findById(1L)).thenReturn(Optional.of(new User(1L, "Ana")));

    assertEquals("Ana", service.getName(1L));
    verify(repo).findById(1L);
  }
}

Checking the welcome email with an ArgumentCaptor

When a user registers, the service saves them and sends a welcome email. Step 1: stub the repository to return the saved user. Step 2: call register. Step 3: capture the Email passed to the mailer. Step 4: assert on its fields: recipient and subject. The test does not care how the service builds the email, only what is sent, so internal refactors will not break it.

java
@ExtendWith(MockitoExtension.class)
class RegistrationServiceTest {
  @Mock UserRepository users;
  @Mock Mailer mailer;
  @Captor ArgumentCaptor<Email> email;
  @Test
  void sendsWelcomeEmail() {
    when(users.save(any())).thenAnswer(inv -> inv.getArgument(0));
    new RegistrationService(users, mailer).register("ana@x.com");
    verify(mailer).send(email.capture());
    assertEquals("ana@x.com", email.getValue().to());
    assertEquals("Welcome!", email.getValue().subject());
  }
}

Simulating a failed payment

You want to know that a declined payment marks the order as failed and never ships it. Step 1: stub the payment client to throw PaymentDeclinedException. Step 2: call placeOrder. Step 3: assert the returned status. Step 4: verify that shipping was never called. Producing this failure with a real payment provider would be slow and hard; with a mock it is one line.

java
@Test
void declinedPaymentFailsOrderAndDoesNotShip() {
  var payments = mock(PaymentClient.class);
  var shipping = mock(ShippingClient.class);
  when(payments.charge(any(), any()))
      .thenThrow(new PaymentDeclinedException("insufficient funds"));
  var service = new OrderService(payments, shipping);

  OrderStatus status = service.placeOrder(new Order("o-1", new BigDecimal("30.00")));

  assertEquals(OrderStatus.PAYMENT_FAILED, status);
  verify(shipping, never()).ship(any());
}

Quick reference

  • when(x.call(arg)).thenReturn(value) for methods that return something
  • doThrow(new Ex()).when(x).voidCall(any()) for void methods
  • If one argument uses a matcher, all must: eq("x"), not "x"
  • verify(x, never()).call(any()) proves something did not happen
  • ArgumentCaptor: verify(x).send(captor.capture()); captor.getValue()
  • Unstubbed calls return 0, false, null or empty collections and Optionals
  • Strict stubs: unused stubs fail with UnnecessaryStubbingException
  • Prefer building the object under test with new over @InjectMocks

Common mistakes

  • Mocking everything, so tests only check that mocks call mocks.
  • Verifying every internal call, making tests break on harmless refactors.
  • Mocking a database layer that an integration test should cover for real.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1An unstubbed mock method returns List<User>. What does it return?

Question 2

2What is wrong with when(repo.find(anyString(), "active"))?

Question 3

3How do you make a void method mailer.send(...) throw in a test?

Question 4

4@InjectMocks cannot find a mock for one dependency. What usually happens?

Question 5

5Which is the best way to test that your JPA repository query is correct?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    GreetingService.greet(long id) returns "Hello, NAME" or "Hello, guest" when the user is missing. Write a test for the missing case.

  2. Exercise 2medium

    Verify that OrderService.place(order) saves the order once and then sends a confirmation, in that order.

  3. Exercise 3hard

    A PriceFetcher retries a flaky client up to 3 times. Test that it succeeds when the first two calls throw and the third returns 9.99, and that the client was called exactly 3 times.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

What is the difference between a mock and a stub?
A stub only returns preset answers. A mock also records calls so you can verify them. Mockito objects can play both roles.
Can Mockito mock final classes and static methods?
Yes. Since Mockito 5 the inline mock maker is the default, so final classes work out of the box, and Mockito.mockStatic can mock static methods inside a try-with-resources block.
What is the difference between @Mock and @MockitoBean?
@Mock is plain Mockito for unit tests without Spring. @MockitoBean (Spring Framework 6.2+, replacing the older @MockBean) puts a mock into the Spring application context for slice and integration tests.
Why do I get UnnecessaryStubbingException?
MockitoExtension uses strict stubs, and one of your when(...) stubs was never used by the code under test. Remove it, or check whether the code took an unexpected path.

Go deeper

ShareXLinkedInWhatsApp