Sub topic 14
Isolating Code with Mocks
Why isolate a class?
Real classes depend on other classes. A checkout service might ask a repository for prices. A repository is a class that loads data, often from a database. If your test uses the real repository, the test needs a running database. It becomes slow, and it can fail for reasons that have nothing to do with the checkout logic.
A test double is a stand-in object that replaces a real dependency during a test. A mock is a test double that you program with answers and that records how it was called. With a mock, you test one class on its own. This is called isolation.
Adding Mockito
Mockito is a popular Java library for creating mocks. Add its JUnit 5 integration to your Maven pom.xml:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>5.14.2</version>
<scope>test</scope>
</dependency>With Gradle, add testImplementation("org.mockito:mockito-junit-jupiter:5.14.2") instead.
A worked example
CheckoutService needs a PriceRepository to look up prices. In the test, a mock replaces the real repository.
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:
| Code | What it does |
|---|---|
| `@ExtendWith(MockitoExtension.class)` | Lets Mockito create mocks before each test |
| `@Mock PriceRepository prices` | Creates a fake `PriceRepository` |
| `when(...).thenReturn(3)` | **Stubs** the mock: when asked for "apple", it returns 3 |
| `assertEquals(12, ...)` | Checks the result of the real `CheckoutService` |
| `verify(prices).priceOf("apple")` | Checks that the service really called the mock |
The test still follows Arrange-Act-Assert. Stubbing the mock is part of Arrange.
Design for mocking
The service receives its repository through the constructor. This is called dependency injection, which means passing in the objects a class needs instead of creating them inside the class. Because of it, the test can easily hand in a mock. If CheckoutService called new DatabasePriceRepository() itself, you could not swap in a mock.
Exercise
You write when(prices.priceOf("apple")).thenReturn(3); but the test calls service.total("pear", 2). What does total return, and why?
Show answer
It returns 0. The mock was only stubbed for "apple", so priceOf("pear") returns the default int value 0, and 0 × 2 = 0. With MockitoExtension's strict stubs, the test also reports the unused "apple" stub as an error.
Exercise
What is the difference between when(...).thenReturn(...) and verify(...)?
Show answer
when(...).thenReturn(...) sets up an answer the mock gives before the code runs (stubbing). verify(...) checks afterwards that the code called the mock in the expected way.