JAVA-220 · Lesson 5 of 12 · 21 min
Mocking with Mockito
▶ Video coming soon A video version of this lesson is on the way.
Kofi had a new request waiting on Thursday, October 7. Every Monday morning he wants PartsDesk to e-mail him the low-stock list with a cost estimate from the supplier's price list. Hamza sketched a ReorderService that would read the counts, ask a supplier price service for prices, add them up and send a message. Then he stopped. "How do I test that? I can't send Kofi an e-mail every time the build runs, and the supplier's prices change every week." Ingrid smiled; this was exactly today's topic. Code that talks to the outside world is tested by giving it pretend versions of the outside world, called test doubles.
Dependencies make testing hard
A class's dependencies are the other objects it needs to do its job: a price list, an e-mail sender, a clock, a database. When the class creates them itself, a test cannot replace them, so testing the class means really calling the supplier and really sending mail. The fix is a design choice called dependency injection: the class receives its dependencies, usually through its constructor, and refers to them through interfaces. Production code passes the real implementations; tests pass stand-ins.
public interface PriceList {
long priceCents(String partCode);
}
public interface Notifier {
void send(String to, String subject, String body);
}
public class ReorderService {
private final PriceList prices;
private final Notifier notifier;
public ReorderService(PriceList prices, Notifier notifier) {
this.prices = prices;
this.notifier = notifier;
}
public long sendWeeklyReport(List<Part> parts) {
long total = 0;
StringBuilder body = new StringBuilder();
for (Part p : parts) {
if (p.isLow()) {
long cost = prices.priceCents(p.code()) * p.suggestedOrder();
total += cost;
body.append(p.code()).append(" x").append(p.suggestedOrder()).append('\n');
}
}
if (total > 0) notifier.send("kofi@secondgear.example", "Weekly reorder", body.toString());
return total;
}
}What this code does
ReorderService depends on two interfaces, PriceList and Notifier, and receives them in its constructor instead of creating them. In production, Hamza will pass a class that reads the supplier's price file and one that sends e-mail. In tests, he can pass anything that implements the two interfaces, which is the opening that test doubles need.
Kinds of test doubles
A test double is any object that stands in for a real dependency during a test, named after the stunt doubles who stand in for actors. The names below, from Gerard Meszaros's book xUnit Test Patterns, are widely used, and the distinctions matter because each kind answers a different question.
| Kind | What it does | Use it to |
|---|---|---|
| Dummy | Fills a parameter and is never used | Satisfy a constructor that needs an object |
| Stub | Returns fixed answers to calls | Control the inputs the code under test receives |
| Fake | A working but simplified implementation | Replace a database with an in-memory map |
| Spy | A real or stub object that also records how it was called | Check calls while keeping real behaviour |
| Mock | An object programmed with expectations about the calls it should receive | Check that the code under test sent the right messages |
Stubs by hand
A stub is the simplest double: an implementation that returns whatever the test needs. Because PriceList has one method, a lambda can be the stub. The test then knows every price exactly, so it can check the total the service computes.
import java.util.*;
public class Main {
interface PriceList { long priceCents(String partCode); }
record Part(String code, int count, int level) {
boolean isLow() { return count <= level; }
int suggestedOrder() { return level * 2 - count; }
}
static long reorderCost(List<Part> parts, PriceList prices) {
long total = 0;
for (Part p : parts) if (p.isLow()) total += prices.priceCents(p.code()) * p.suggestedOrder();
return total;
}
public static void main(String[] args) {
Map<String, Long> fixed = Map.of("TUBE-700x25", 450L, "PAD-ROAD", 300L, "CHAIN-11", 2200L);
PriceList stub = code -> fixed.get(code);
List<Part> parts = List.of(new Part("TUBE-700x25", 15, 40), new Part("PAD-ROAD", 32, 15), new Part("CHAIN-11", 6, 10));
long cost = reorderCost(parts, stub);
long expected = 450L * 65 + 2200L * 14;
System.out.println("Reorder cost: " + cost + " cents, expected " + expected + ": " + (cost == expected ? "PASS" : "FAIL"));
}
}Reorder cost: 60050 cents, expected 60050: PASS
What this code does
The stub is a lambda that looks each part code up in a fixed map, so the test knows exactly what price the service will see. Only the tubes and the chains are low, needing 65 and 14 more, so the expected total is 450 times 65 plus 2200 times 14, worked out independently of the code. Real supplier prices change weekly, which would make a test against them unrepeatable.
Mocks by hand: checking the calls
The service's other job is to send a message, and nothing is returned to check. What the test must check is that send was called once, to Kofi, with the right body, and that it is not called at all when nothing is low. A recording mock stores every call so the test can inspect them afterwards. This style is called interaction testing, as opposed to state testing, which checks return values and object state.
import java.util.*;
public class Main {
interface PriceList { long priceCents(String partCode); }
interface Notifier { void send(String to, String subject, String body); }
record Part(String code, int count, int level) {
boolean isLow() { return count <= level; }
int suggestedOrder() { return level * 2 - count; }
}
record Call(String to, String subject, String body) { }
static class RecordingNotifier implements Notifier {
final List<Call> calls = new ArrayList<>();
public void send(String to, String subject, String body) { calls.add(new Call(to, subject, body)); }
}
static long sendWeeklyReport(List<Part> parts, PriceList prices, Notifier notifier) {
long total = 0;
StringBuilder body = new StringBuilder();
for (Part p : parts) {
if (p.isLow()) {
total += prices.priceCents(p.code()) * p.suggestedOrder();
body.append(p.code()).append(" x").append(p.suggestedOrder()).append("; ");
}
}
if (total > 0) notifier.send("kofi@secondgear.example", "Weekly reorder", body.toString().strip());
return total;
}
public static void main(String[] args) {
PriceList prices = code -> 450;
RecordingNotifier mock = new RecordingNotifier();
sendWeeklyReport(List.of(new Part("TUBE-700x25", 15, 40), new Part("BELL", 9, 4)), prices, mock);
System.out.println("Calls when tubes are low: " + mock.calls.size());
System.out.println(" " + mock.calls.get(0));
RecordingNotifier quiet = new RecordingNotifier();
sendWeeklyReport(List.of(new Part("BELL", 9, 4)), prices, quiet);
System.out.println("Calls when nothing is low: " + quiet.calls.size());
}
}Calls when tubes are low: 1 Call[to=kofi@secondgear.example, subject=Weekly reorder, body=TUBE-700x25 x65;] Calls when nothing is low: 0
What this code does
RecordingNotifier implements Notifier by adding each call to a list instead of sending anything, so the test can count the calls and read their arguments. The first run has one low part and records exactly one message to Kofi naming the tubes and the order of 65. The second run has nothing low and records no calls, which proves the service does not send an empty report.
Mockito
Writing a recording class for every interface gets tedious, so most Java teams use Mockito, a library that creates stubs and mocks at run time for any interface or class. The current release in late 2026 is Mockito 5.24. mock(PriceList.class) returns an object that answers every call with a default value, such as 0 or null. when(...).thenReturn(...) stubs a call, and verify(...) checks that a call happened. Mockito is added with testImplementation("org.mockito:mockito-core:5.24.0"), or mockito-junit-jupiter for the JUnit integration.
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class ReorderServiceTest {
@Mock PriceList prices;
@Mock Notifier notifier;
@InjectMocks ReorderService service;
@Test
void sendsOneReportWhenPartsAreLow() {
when(prices.priceCents("TUBE-700x25")).thenReturn(450L);
long total = service.sendWeeklyReport(List.of(new Part("TUBE-700x25", 15, 40)));
assertEquals(450L * 65, total);
verify(notifier).send(eq("kofi@secondgear.example"), eq("Weekly reorder"), contains("TUBE-700x25 x65"));
verifyNoMoreInteractions(notifier);
}
@Test
void sendsNothingWhenNothingIsLow() {
service.sendWeeklyReport(List.of(new Part("BELL", 9, 4)));
verify(notifier, never()).send(anyString(), anyString(), anyString());
}
}What this code does
The Mockito extension creates the two @Mock fields and injects them into a new ReorderService through its constructor before each test. when and thenReturn stub one price, and verify checks the message's recipient and subject exactly and its body with contains, so the test does not depend on the body's exact layout. never() asserts that send was not called at all when nothing is low.
Argument matchers such as eq, anyString and contains say which arguments a stub or verification accepts; if one argument uses a matcher, all of them must. When a test needs the actual argument to inspect it in detail, an ArgumentCaptor captures it during verify. Mockito's JUnit extension uses strict stubs: a when(...) that the code never uses fails the test with UnnecessaryStubbingException, which keeps tests free of stale setup.
$ ./gradlew :partsdesk:test --tests ReorderServiceTestReorderServiceTest > sendsOneReportWhenPartsAreLow() PASSED
ReorderServiceTest > sendsNothingWhenNothingIsLow() FAILED
org.mockito.exceptions.verification.NeverWantedButInvoked:
notifier.send(
<any string>,
<any string>,
<any string>
);
Never wanted here:
-> at org.secondgear.parts.ReorderServiceTest.sendsNothingWhenNothingIsLow(ReorderServiceTest.java:31)
But invoked here:
-> at org.secondgear.parts.ReorderService.sendWeeklyReport(ReorderService.java:24) with arguments: ["kofi@secondgear.example", "Weekly reorder", ""]
2 tests completed, 1 failedWhat this code does
With the price stubbed and the notifier mocked, both tests pass without touching the network or the supplier's file. The second line of output shows a failure from an earlier version of the service that sent an empty report: Mockito's never() verification names the unwanted call and its arguments. Messages like this are why verify is precise about arguments.
One practical note for current Java: Mockito 5 creates mocks with an agent that it attaches while the tests run, and since Java 21 the JVM prints a warning when an agent is loaded that way, because a future Java release will forbid it. Mockito's documentation shows how to configure the build to pass Mockito as a -javaagent to the test JVM instead, which removes the warning; the secondgear build does this in its test task.
Doubles for time and randomness
The clock is a dependency too. Code that calls LocalDate.now() gives a different answer every day, so its tests cannot be repeatable. The standard library already has the injection point: java.time.Clock. Production code asks a Clock for the time, and tests pass Clock.fixed, which always returns the same instant. Random numbers work the same way: inject a Random, and give tests one with a fixed seed.
import java.time.*;
public class Main {
static class Rental {
private final LocalDate due;
private final Clock clock;
Rental(LocalDate due, Clock clock) { this.due = due; this.clock = clock; }
boolean isOverdue() { return LocalDate.now(clock).isAfter(due); }
}
static Clock fixedAt(String date) {
return Clock.fixed(LocalDate.parse(date).atStartOfDay(ZoneOffset.UTC).toInstant(), ZoneOffset.UTC);
}
public static void main(String[] args) {
LocalDate due = LocalDate.of(2027, 10, 9);
System.out.println("On Oct 9, overdue? " + new Rental(due, fixedAt("2027-10-09")).isOverdue());
System.out.println("On Oct 10, overdue? " + new Rental(due, fixedAt("2027-10-10")).isOverdue());
System.out.println("Fixed clock reads: " + LocalDate.now(fixedAt("2027-10-10")));
}
}On Oct 9, overdue? false On Oct 10, overdue? true Fixed clock reads: 2027-10-10
What this code does
Rental asks its injected Clock for today's date instead of calling the system clock, so the test controls what today means. A fixed clock set to October 9 shows that a rental due that day is not overdue, and one set to October 10 shows that it is. The same test gives the same answers in 2027, 2030 or any other year, which a test using the real clock could not.
Using mocks well
Mocks are powerful and easy to overuse. A test that mocks everything checks only that the code calls what it calls today, so any internal change breaks it even when behaviour is unchanged. Experienced testers follow a few guidelines.
- Prefer real objects for simple values and data classes; never mock a record or a List.
- Use stubs to control inputs, and verify only the interactions that are the point of the behaviour, such as sending the report.
- Prefer fakes, such as an in-memory repository, when the real thing is slow but the logic around it matters.
- Do not mock types you do not own, such as a library's HTTP client; wrap them in your own small interface and mock that.
- If a test needs five mocks, the class probably has too many responsibilities.
Try it yourself
A stub for the supplier
Create a stub PriceList in main, as a lambda, that returns 450 cents for TUBE-700x25, 2200 cents for CHAIN-11 and 0 for any other code, and pass it to reorderCost.
The program should print Reorder cost: 60050 cents.
import java.util.*;
public class Main {
interface PriceList { long priceCents(String partCode); }
record Part(String code, int count, int level) {
boolean isLow() { return count <= level; }
int suggestedOrder() { return level * 2 - count; }
}
static long reorderCost(List<Part> parts, PriceList prices) {
long total = 0;
for (Part p : parts) if (p.isLow()) total += prices.priceCents(p.code()) * p.suggestedOrder();
return total;
}
public static void main(String[] args) {
PriceList stub = code -> 0;
List<Part> parts = List.of(new Part("TUBE-700x25", 15, 40), new Part("CHAIN-11", 6, 10), new Part("BELL", 2, 4));
System.out.println("Reorder cost: " + reorderCost(parts, stub) + " cents");
}
}Try it yourself
Verify the message
RecordingNotifier records calls. After remind runs, check the recorded calls: print PASS if exactly one call was made and its to is odile@secondgear.example, otherwise print FAIL and the number of calls.
The program should print PASS.
import java.util.*;
public class Main {
interface Notifier { void send(String to, String subject); }
record Call(String to, String subject) { }
static class RecordingNotifier implements Notifier {
final List<Call> calls = new ArrayList<>();
public void send(String to, String subject) { calls.add(new Call(to, subject)); }
}
static void remind(int overdueBikes, Notifier n) {
if (overdueBikes > 0) n.send("odile@secondgear.example", overdueBikes + " rental bikes overdue");
}
public static void main(String[] args) {
RecordingNotifier mock = new RecordingNotifier();
remind(2, mock);
System.out.println("FAIL " + mock.calls.size());
}
}Common mistakes
MistakeA class that creates its own e-mail sender, clock or database connection.
InsteadInject dependencies through the constructor, behind interfaces, so tests can pass doubles.
MistakeCalling LocalDate.now() in code that tests must check.
InsteadInject a java.time.Clock and use Clock.fixed in tests.
MistakeMocking records, lists and other simple values.
InsteadUse real objects for values; mock only collaborators with behaviour.
MistakeVerifying every call the code makes.
InsteadVerify only the interactions that are the point of the behaviour.
MistakeMocking a third-party library's classes directly.
InsteadWrap them in your own small interface and mock that instead.
Summary and key terms
- Code that talks to the outside world is tested by injecting its dependencies, usually through the constructor and behind interfaces, so tests can pass test doubles.
- Dummies fill parameters, stubs return fixed answers, fakes are simplified working implementations, spies record calls on real behaviour and mocks check the calls they receive.
- State testing checks results; interaction testing checks messages sent to collaborators.
- Mockito creates doubles at run time: mock() makes one, when(...).thenReturn(...) stubs a call, verify(...) checks a call, matchers such as eq and anyString describe arguments, ArgumentCaptor captures them, and strict stubs reject unused stubbing.
- Time and randomness are dependencies too, handled with java.time.Clock and seeded Random.
- Good tests mock little: real values, verified interactions only where they matter, and wrappers around libraries you do not own.
- Dependency
- An object another class needs to do its work, such as a price list or a clock.
- Dependency injection
- Passing a class its dependencies, usually through its constructor, instead of letting it create them.
- Test double
- Any object that stands in for a real dependency in a test.
- Stub
- A double that returns fixed answers to calls.
- Fake
- A simplified but working implementation, such as an in-memory repository.
- Mock
- A double that checks the calls it receives.
- Spy
- A double that keeps real or stub behaviour and records how it was called.
- Interaction testing
- Checking the calls code makes to its collaborators rather than its results.
- Mockito
- The most widely used Java library for creating stubs and mocks.
- Argument matcher
- A Mockito expression such as anyString() describing which arguments are accepted.
- Clock.fixed
- A java.time.Clock that always returns the same instant, for repeatable tests.
Practice problems
Work each problem on paper first, then reveal the answer to check.
Why can't ReorderService be tested well if it creates its own e-mail sender?
Show answer
The test cannot replace it, so every test run would send real e-mail.
What is the difference between a stub and a mock?
Show answer
A stub supplies answers to the code; a mock checks the calls the code makes.
Which Mockito call checks that a method was never called?
Show answer
verify(mock, never()).method(...).
How do you make code that uses today's date testable?
Show answer
Inject a java.time.Clock and pass Clock.fixed in tests.
What does a test that needs five mocks usually suggest?
Show answer
The class under test has too many responsibilities.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.