Fakes, Stubs and Mocks Without Over-Mocking
Pick the right test double for each collaborator — a fake with real behaviour, a stub with canned answers, or a mock that records calls — and keep tests from breaking on every refactor.
Contentsand lesson path
On this page
- Why it matters
- Three doubles you actually need
- Choosing between them
- How over-mocking hurts
- Check your understanding
- Apply it
- Review prompt
Lessons of Software Testing Fundamentals
- Why Automated Tests, and What to Test First Concept · 15 min
- Framework Essentials: Asserts, Fixtures and Parametrized Cases (pytest or Vitest) Worked example · 25 min
- Fakes, Stubs and Mocks Without Over-Mocking Concept · 20 min
- Lab: Testing Endpoints with a Test Client Lab · 25 min
- Reading Coverage and Choosing Test Levels Worked example · 15 min
- Check: Find the Missing Test Knowledge check · 8 questions
What you will learn
- Replace slow or external collaborators with test doubles (fakes, stubs or mocks), and explain when a fake is preferable to a mock.
Prerequisites: Python Foundations
01. Why it matters
A unit test earns its name by being fast and repeatable: the same code, the same result, every time, in milliseconds. The moment the code under test talks to a collaborator — a database, a mail server, the system clock, a payment provider — both properties are at risk. The collaborator is slow, it may be down, it costs money to call, and its answers change between runs: a test that asks for today's date fails precisely around midnight.
The fix is not to skip testing code with collaborators; almost every interesting code has them. The fix is to substitute the collaborator during the test with something you control. Any object that stands in for the real thing is called a test double, the way a stunt double stands in for an actor. The frontend testing skill met the same idea at the network boundary, mocking the wire rather than your code; a backend swaps collaborators at the seams the design provides, such as constructor arguments or dependency injection.
Choosing which kind of double is the skill this lesson teaches, because the wrong choice either tests nothing or ties your suite to the implementation so tightly that harmless refactors break it.
02. Three doubles you actually need
Books on testing define five or six kinds of double, but three cover daily work, and the differences between them matter more than the names:
- A fake is a working, lightweight implementation of the same interface. It keeps real state and real behaviour, just not production-grade: an in-memory list where the real repository uses PostgreSQL.
- A stub supplies canned answers to questions the code under test asks. It keeps no record and computes nothing:
today()returns one fixed date, a client returns one fixed reply. - A mock records every call made on it, so the test can verify that something was sent and what it contained. The mock in Python's standard library is
unittest.mock.Mock; in Vitest it isvi.fn().
One service makes all three plain. ReadingList stores books through a repository, stamps them with a date from a clock, and may notify a reader:
from dataclasses import dataclass
from datetime import date
from typing import Protocol
from unittest.mock import Mock # used in part 2, by the test code only
@dataclass(frozen=True)
class Book:
title: str
added_on: date
class InMemoryBookRepository:
"""A fake: real add/list behaviour, no database."""
def __init__(self) -> None:
self._books: list[Book] = []
def add(self, book: Book) -> None:
self._books.append(book)
def all(self) -> list[Book]:
return list(self._books)
class FixedClock:
"""A stub: hands out one canned answer and keeps no record."""
def today(self) -> date:
return date(2026, 10, 24)
class Notifier(Protocol):
"""The seam: anything with this send method can be injected."""
def send(self, *, to: str, subject: str) -> None: ...
@dataclass
class ReadingList:
repo: InMemoryBookRepository
clock: FixedClock
notifier: Notifier # required: production passes a real mailer
def add_book(self, title: str, notify: str | None = None) -> Book:
book = Book(title=title, added_on=self.clock.today())
self.repo.add(book)
if notify is not None:
self.notifier.send(to=notify, subject=f"Added {title}")
return bookrepo = InMemoryBookRepository()
service = ReadingList(repo=repo, clock=FixedClock(), notifier=Mock(spec=["send"]))
service.add_book("The Pragmatic Programmer")
service.add_book("Refactoring", notify="[email protected]")
print("state the fake kept:", repo.all())
print("calls the mock recorded:", service.notifier.mock_calls)
service.notifier.send.assert_called_once()
print("verified: one send, and only when an address was given")state the fake kept: [Book(title='The Pragmatic Programmer',
added_on=datetime.date(2026, 10, 24)), Book(title='Refactoring',
added_on=datetime.date(2026, 10, 24))]
calls the mock recorded: [call.send(to='[email protected]',
subject='Added Refactoring')]
verified: one send, and only when an address was givenNotice what each double contributed. The fake accepted two books and can answer questions about them afterwards, so a test can assert on stored state — the outcome a user cares about. The stub made the run deterministic: every book is stamped with the same date, and the test can assert on it without knowing what day it is. The mock proved a property no stored state can express: exactly one email was sent, and only because an address was supplied.
Mock can play stub too: clock = Mock() with clock.today.return_value = date(2026, 10, 24) answers every call identically. Give it spec=SomeClass and it rejects calls that class does not have, which catches typos when the interface changes. In Vitest, vi.fn() is the same recorder: expect(send).toHaveBeenCalledTimes(1) and expect(send).toHaveBeenCalledWith(address, subject) mirror assert_called_once() and assert_called_once_with(...).
03. Choosing between them
Ask two questions about the collaborator. First: is the behaviour you want to check an input or an output of the code under test? A stub controls indirect input — answers your code consumes, like the date or an exchange rate. A mock observes indirect output — calls your code makes, like sending mail or charging a card. Second: does the test need the collaborator to behave realistically over a whole scenario? If yes, write a fake and assert on state at the end.
This gives a simple order of preference:
- Prefer a fake for collaborators you own that carry state: repositories, outboxes, caches. Tests read back outcomes, stay readable, and keep working when the internals change. The reading-list lab in the next lesson injects exactly such a fake into a FastAPI app.
- Use a stub for indirect inputs you need pinned: clocks, randomness, third-party replies in tests of your parsing and decision code.
- Reach for a mock when the interaction itself is the requirement — one email, one charge, the right address — and keep the assertions few and meaningful.
04. How over-mocking hurts
The failure mode of mocks is brittleness. Suppose every test of ReadingList verified the exact sequence repo.add then notifier.send with exact arguments. A harmless refactor — folding two repository calls into one, reordering an internal step — leaves every observable outcome identical, yet the suite goes red, because the tests were verifying the implementation's choreography rather than its results. Teams then stop trusting red, which is the moment a suite stops being a safety net.
State-based tests on a fake survive the same refactor untouched: the book is stored, the state is right, the test is green. That resilience is the practical meaning of the advice to prefer fakes. When you do verify interactions, verify the few that are contractual: one charge, the customer's address. A test asserting six calls in order is a transcript of today's implementation, not a promise about behaviour.
One more boundary rule keeps suites honest: double the collaborator, never the code under test. If you find yourself mocking the very function whose behaviour the file name promises to check, the test now checks the mock. The same argument, and its frontend twin of mocking your own API client, is made in the network-mocking lesson.
05. Check your understanding
06. Apply it
List the collaborators of a service you are building, and put each into one of three columns: needs a fake, needs a stub, needs a mock. Justify every mock in writing — what contractual interaction does it verify? Then write one test that would break under a harmless internal refactor, if you can find one, and rewrite it against a fake's state instead. You will use your fake again in the endpoint lab, injected through a dependency override.
07. Review prompt
Without looking back: define a test double, then a fake, a stub and a mock, each in one sentence. Give one situation where a fake beats a mock, and one where only a mock can verify the requirement. Explain what breaks when a suite over-mocks, and what "double the collaborator, never the code under test" means.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.