Stop 11 · Git, Build Tools & TestingTopics · 7/10

Mocking with Mockito

Part of the Java Roadmap

In short

Your TransferService talks to a database and sends SMS alerts. You don't want unit tests hitting a real database or texting real customers. Mockito gives you convincing fakes so you can test your logic alone.

Mockito creates fake versions of dependencies, such as a repository or external API, so you can test one class in isolation and verify how it uses its collaborators.

The jaadu, as a film director with a megaphone, guides a cardboard cut-out stand-in on a small film set.

Think of it like this

The rehearsal stand-in

When a film crew rehearses a scene, they don't call in the superstar. A stand-in takes the spot, says the lines they're given and lets the director check the lighting and camera. A Mockito mock is that stand-in: it returns what you script and remembers exactly what it was asked to do.

Watch it happen

A transfer test with mocks

Test
TransferService
Mock repo
Mock SMS

when(findById).thenReturn

1/5The test scripts the mock: asked for A1 or A2, return these accounts.

The big ideas

What you need to know

@Mock and @InjectMocks

@Mock creates fakes. @InjectMocks builds the real class and passes the mocks into its constructor.

Stubbing

when(repo.findById("A1")).thenReturn(Optional.of(acc)) scripts an answer. thenThrow scripts a failure.

Verifying

verify(sms).send(...) checks a call happened. verifyNoInteractions(sms) checks it never did.

Mock the edges only

Mock things your class talks to, like repositories, HTTP clients and clocks. Don't mock simple value objects or the class under test.

See it in code

Walk through the code

java
1import org.junit.jupiter.api.Test;2import org.junit.jupiter.api.extension.ExtendWith;3import org.mockito.InjectMocks;4import org.mockito.Mock;5import org.mockito.junit.jupiter.MockitoExtension;6 7import java.util.Optional;8 9import static org.junit.jupiter.api.Assertions.*;10import static org.mockito.Mockito.*;11 12@ExtendWith(MockitoExtension.class)13class TransferServiceTest {14    @Mock AccountRepository repo;15    @Mock SmsSender sms;16    @InjectMocks TransferService service;17 18    @Test19    void transferMovesMoneyAndSendsSms() {20        Account from = new Account("A1", 5000);21        Account to = new Account("A2", 1000);22        when(repo.findById("A1")).thenReturn(Optional.of(from));23        when(repo.findById("A2")).thenReturn(Optional.of(to));24 25        service.transfer("A1", "A2", 2000);26 27        assertEquals(3000, from.getBalance());28        assertEquals(3000, to.getBalance());29        verify(repo).save(from);30        verify(repo).save(to);31        verify(sms).send(eq("A2"), contains("2000"));32    }33 34    @Test35    void unknownAccountThrowsAndSendsNothing() {36        when(repo.findById("X9")).thenReturn(Optional.empty());37        assertThrows(IllegalArgumentException.class,38                () -> service.transfer("X9", "A2", 100));39        verifyNoInteractions(sms);40    }41}

1/5The Mockito extension creates the two mocks and injects them into a real TransferService.

Testing TransferService without a database or SMS gateway. Add mockito-junit-jupiter as a test dependency.

Save yourself the pain

Common mistakes

Oops

Mocking everything, including the class you are testing.

Do this instead

Use the real class under test and mock only its collaborators.

Oops

Mixing raw values and matchers: verify(sms).send("A2", contains("2000")).

Do this instead

If one argument uses a matcher, all must. Use eq("A2") for the plain value.

Oops

Stubbing calls the test never uses.

Do this instead

MockitoExtension's strict stubs fail the test with UnnecessaryStubbingException. Remove unused when(...) lines.

Your mission

Mock an order service

~45 min

Quick check

What does verify(sms).send(eq("A2"), anyString()) check?

Go deeper

  1. 1Mock a repository with when(...).thenReturn(...) in a service test.
  2. 2Use verify() to check a method was called with the right arguments.
  3. 3Use @Mock and @InjectMocks with the Mockito JUnit 5 extension.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge