Notes
The problem
Imagine a checkout that charges a payment gateway, then emails a receipt, and checks coupon expiry against today's date. In a unit test, the real gateway is slow, costs money and may be down. The real email service sends real emails. The real clock changes, so a test about expiry passes today and fails next month. And you cannot make the real gateway decline a card on demand, which is exactly the case you most need to test.
- payment gateway: slow, costs money, may be down email: sends real emails
- clock: today changes, so "expired?" changes
- database: needs setup, slow
- and you cannot make the real
- gateway DECLINE on demand
The idea
A test double is any object that stands in for a real one, like a stunt double in a film. Gerard Meszaros named five kinds. A dummy is passed in but never used. A stub returns canned answers: charge returns true. A spy is a stub that also records how it was called. A mock is set up with expected calls and verifies them. A fake is a working but lighter version, like an in memory database. People often say mock for all five; interviewers like the distinctions.
- dummy passed in, never used
- stub returns canned answers "charge() → true"
- spy a stub that records how it was called
- mock expects certain calls and verifies them
- fake a working light version: in-memory DB
Stubs
A stub controls what the dependency answers. With Mockito in Java, create a mock of the payment gateway interface, then say: when charge is called with order seven and four thousand nine hundred ninety nine cents, return false. Pass it to the checkout, and assert that pay returns false. The card declined case, impossible to produce with a real gateway on demand, is now a one line setup. That is the main power of stubs.
PaymentGateway gw =
mock(PaymentGateway.class);
when(gw.charge(7, 4999))
.thenReturn(false);
var c = new Checkout(gw, email);
assertFalse(c.pay(7, 4999));
// now "card declined" is a
// one-line test Mocks
Sometimes the result is a call, not a value. After a successful payment, the checkout must send exactly one receipt email. With Python's unittest mock, make the gateway's charge return true, call pay, then assert that email dot send was called once with Alice's address and the message order seven paid. In the declined case, assert it was not called at all. These three Python tests run and pass in about ten milliseconds.
gateway = Mock() gateway.charge.return_value = True email = Mock() Checkout(gateway, email).pay(7, 4999) email.send.assert_called_once_with( "alice@shoprung.test", "Order 7 paid") # declined: email.send # .assert_not_called()
State vs interaction
There are two styles. State testing checks the result or the new state: the total is forty nine ninety nine. Interaction testing checks the calls: the email service was called with these arguments. Prefer state testing, because it survives refactoring. Use interaction testing when the call itself is the behaviour you care about, like sending an email or charging a card, where there is no other result to look at.
- state testing: check the result or the new state assert total == 4999
- interaction testing: check the calls made verify(email).send(...)
- prefer state; verify calls
- only when the call IS the behaviour (email, payment)
Control time
Time is a dependency too. If code reads the real clock inside, a test about expiry depends on the day you run it. Pass today in instead. Here the coupon check takes the expiry date and today as arguments. Test welcome fifteen on the first of January twenty twenty six: expired. On the thirty first of December itself: still valid, matching ShopRung. In Java, inject a java dot time Clock and use Clock dot fixed in tests. The same goes for random numbers.
def coupon_problem(expires_on,
today):
if expires_on and today >
expires_on:
return "This coupon has
expired"
coupon_problem(date(2025,12,31),
date(2026, 1, 1)) # expired
# 31 Dec itself → None (valid)
# Java: pass a java.time.Clock Fakes
A fake is a real, working implementation that takes a shortcut. A fake order repository stores orders in a hash map instead of a database. Unlike a stub, it behaves consistently across many calls: save an order, then find it. Fakes suit tests with several steps, and are shared across many tests. Other common fakes: an in memory message queue, and WireMock for HTTP services, which you will meet in Part four.
class FakeOrders implements
OrderRepository {
Map<Long, Order> rows =
new HashMap<>();
public void save(Order o) {
rows.put(o.id(), o); }
public Optional<Order> find(
long id) { return Optional
.ofNullable(rows.get(id)); }
} Over-mocking
The trap is over mocking. Mock every class and verify every call, and the test becomes a mirror of the code: any refactor breaks it, and bugs in how real parts fit together are never seen. The rule: mock at the edges of your system, the things you do not own or cannot control, like the network, payment providers, email, the clock and randomness. Use real objects for your own simple classes, and cover the joins with integration tests.
- mock every class, verify
- every call → test mirrors the code any refactor breaks it real bugs between parts are never seen
- mock at boundaries you do
- not own: network, payment, email, clock, randomness
Common mistakes
How test doubles go wrong. Mocking the very class under test. Mocking simple value objects that could just be created. Verifying every call, so tests break on harmless changes. Stubs that drift from the real API, returning shapes the real service never sends; contract tests in Part four guard against that. Leaving the real clock in. And no integration test anywhere that checks the real dependency still works.
- mocking the class under test
- mocking value objects and simple classes
- verify() on every call
- stubs that never match the real API (drift)
- real clock in tests
- no integration test to check the real dependency
Say it like this
In the interview: a stub returns canned data so I can control inputs, like a declined card. A mock also verifies interactions, like exactly one receipt email. A fake is a light working version, like an in memory database. I mock only boundaries I do not own, like payment, email and the network, inject the clock instead of reading it, prefer checking results over calls, and cover the real connections with integration tests.
- "A stub returns canned data
- so I can control inputs, like
- a declined card. A mock also verifies interactions, like
- one receipt email sent. A fake is a light working
- version, like an in-memory DB.
- I mock only boundaries I do
- not own, inject the clock, and cover the joins elsewhere."