Sub topic 14
Isolating Code with Mocks
So far, the classes you tested worked alone. Calculator needed nothing else to add two numbers. Real code is rarely that simple. A checkout service might ask a database for prices. An order service might charge a credit card and send an email. You do not want a unit test to touch a real database or charge a real card.
This chapter shows how to swap those helpers for stand-ins that you control. A stand-in like this lets you test one class by itself.
Why Isolation Matters
A dependency is another object that your class needs to do its job. If CheckoutService calls a PriceRepository, then the repository is a dependency of the service.
Testing with real dependencies causes problems:
- Slow tests. A database or network call can take seconds. A unit test should take milliseconds.
- Flaky tests. A flaky test passes sometimes and fails other times. A network outage can make one fail even when your code is correct.
- Unclear failures. When the test fails, you can't tell if the bug is in your class or in the dependency.
- Side effects. A side effect is a change outside the test, such as a real email sent to a customer.
The fix is a test double. A test double is a fake object that takes the place of a real dependency during a test. The name comes from a "stunt double" in films.
Kinds of Test Doubles
People use several names for test doubles. You will see these words in books and code reviews.
| Name | What it does | Example |
|---|---|---|
| Dummy | Fills a parameter but is never used | Passing `null` or an empty object to a constructor |
| Stub | Returns fixed answers you choose | `priceOf("apple")` always returns `3` |
| Fake | A simple working version | An in-memory list instead of a database |
| Mock | Records calls so you can check them later | Confirm `send()` was called once |
| Spy | Wraps a real object and records calls to it | A real list that also tracks `add()` calls |
You don't need to remember every name. In practice, the Mockito library makes one object that can act as a stub and a mock at the same time. Mockito is the most popular library for creating test doubles in Java.
Adding Mockito to Your Project
Mockito ships a module that works with JUnit 5, called mockito-junit-jupiter. Add it next to your JUnit dependency.
For Maven, add this to pom.xml:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>5.14.2</version>
<scope>test</scope>
</dependency>For Gradle with the Kotlin DSL, add this line to the dependencies block in build.gradle.kts:
dependencies {
testImplementation("org.mockito:mockito-junit-jupiter:5.14.2")
}This module pulls in Mockito's core library for you.
Your First Mock
Here is a small service that depends on a price repository. The test replaces the repository with a mock.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
interface PriceRepository {
int priceOf(String product);
}
class CheckoutService {
private final PriceRepository prices;
CheckoutService(PriceRepository prices) {
this.prices = prices;
}
int total(String product, int quantity) {
return prices.priceOf(product) * quantity;
}
}
@ExtendWith(MockitoExtension.class)
class CheckoutServiceTest {
@Mock
PriceRepository prices;
@Test
void totalMultipliesPriceByQuantity() {
when(prices.priceOf("apple")).thenReturn(3);
CheckoutService service = new CheckoutService(prices);
assertEquals(12, service.total("apple", 4));
verify(prices).priceOf("apple");
}
}Here is what each part does:
@ExtendWith(MockitoExtension.class)connects Mockito to JUnit. A later chapter explains extensions in detail. For now, it tells JUnit to let Mockito prepare the test.@Mockasks Mockito to create a fakePriceRepositorybefore each test. You never write a class that implements the interface.when(...).thenReturn(3)is stubbing. Stubbing means telling the mock what to return for a given call.- The test passes the mock into the service's constructor. This is called dependency injection: the service receives its dependencies from outside instead of creating them.
verify(prices).priceOf("apple")checks that the service called the mock with"apple"exactly once.
The diagram below shows the flow of one test.
A Bigger Example: Stubbing, Throwing, and Never
Real services often have more than one dependency. This OrderService charges a customer and sends an email only if the payment works.
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
interface PaymentGateway {
boolean charge(String customer, int amount);
}
interface EmailSender {
void send(String to, String message);
}
class OrderService {
private final PaymentGateway payments;
private final EmailSender email;
OrderService(PaymentGateway payments, EmailSender email) {
this.payments = payments;
this.email = email;
}
boolean placeOrder(String customer, int amount) {
boolean paid = payments.charge(customer, amount);
if (paid) {
email.send(customer, "Thanks for your order");
}
return paid;
}
}
@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
@Mock
PaymentGateway payments;
@Mock
EmailSender email;
@Test
void successfulPaymentSendsEmail() {
when(payments.charge("ana", 50)).thenReturn(true);
OrderService service = new OrderService(payments, email);
assertTrue(service.placeOrder("ana", 50));
verify(email).send(eq("ana"), anyString());
}
@Test
void failedPaymentSendsNoEmail() {
when(payments.charge(anyString(), anyInt())).thenReturn(false);
OrderService service = new OrderService(payments, email);
assertFalse(service.placeOrder("ben", 20));
verify(email, never()).send(anyString(), anyString());
}
@Test
void gatewayErrorIsPassedOn() {
when(payments.charge("cy", 10))
.thenThrow(new IllegalStateException("gateway down"));
OrderService service = new OrderService(payments, email);
assertThrows(IllegalStateException.class,
() -> service.placeOrder("cy", 10));
}
}This example introduces some new tools:
- Argument matchers such as
anyString(),anyInt(), andeq("ana")match a range of values instead of one exact value. never()checks that a method was not called. Usetimes(2)to check for an exact number of calls.thenThrow(...)makes the mock throw an exception. This lets you test error paths that are hard to cause with a real system.
If you never stub a method, the mock returns a default value. It returns false for boolean, 0 for numbers, null for most objects, and an empty list for List.
Common Mistakes
Mixing matchers and plain values
If one argument uses a matcher, every argument must use one. This line fails at runtime:
verify(email).send("ana", anyString());Wrap the plain value in eq() instead: verify(email).send(eq("ana"), anyString());.
Unused stubs
MockitoExtension runs in strict mode. If you stub a call that the test never uses, Mockito fails the test with an UnnecessaryStubbingException. This warning is useful: it often means your test no longer checks what you think it checks. Delete the extra stub.
Mocking the class under test
Mock the dependencies, never the class you are testing. If you mock OrderService, you are testing Mockito's fake, not your code.
Verifying too much
Checking every single call ties the test to how the code works inside. Small refactors then break tests even though the behavior is still correct. Check the return value first. Use verify for calls that matter as results, such as "an email was sent."
Mocks Without the Extension
You can also create a mock with a plain method call. This version needs no @ExtendWith and no @Mock:
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
class CheckoutServiceManualMockTest {
@Test
void totalForOneItem() {
PriceRepository prices = mock(PriceRepository.class);
when(prices.priceOf("pear")).thenReturn(5);
assertEquals(5, new CheckoutService(prices).total("pear", 1));
}
}This style is handy for a single test. The extension version is cleaner when many tests share the same mocks, because Mockito creates fresh mocks before each test, just like @BeforeEach would.
Exercise
In OrderServiceTest, write a test that checks the email message is exactly "Thanks for your order" when payment for customer "dee" of amount 30 succeeds.
Show answer
Stub the gateway and verify with exact values: when(payments.charge("dee", 30)).thenReturn(true); OrderService service = new OrderService(payments, email); service.placeOrder("dee", 30); verify(email).send("dee", "Thanks for your order"); Both arguments are plain values, so no matchers are needed.
Exercise
A test contains the line verify(payments).charge(anyString(), 100); and fails with an error about invalid matcher use. Why, and how do you fix it?
Show answer
One argument uses a matcher (anyString()) and the other is a plain value (100). Mockito requires all arguments to be matchers if any are. Fix it with verify(payments).charge(anyString(), eq(100));
Exercise
Which of these should you usually mock in a unit test: a java.util.ArrayList, a class that sends SMS messages, or a class that reads the current time from the system clock?
Show answer
Mock the SMS sender, because it has side effects, and the clock, because its value changes on every run and makes results unpredictable. Use a real ArrayList, since it is fast, predictable, and has no side effects.