Sub topic 2
Fakes, stubs, and mocks: what each one is for
This chapter assumes you can write pytest tests, read basic Python classes and exceptions, and pass a dependency as an argument. Earlier chapters explained why live model calls make poor unit tests. This chapter names the tools you use instead. It covers what each kind of test double does, which question each one answers, and where each goes wrong in LLM code. Later chapters build the specific fakes and recordings.
What a test double is
A test double is an object that stands in for a real dependency during a test. The name comes from "stunt double". In LLM code, the dependency is usually the model client: the object that sends a prompt and returns text.
Test authors use a handful of terms for doubles, and people often mix them up. The terms below follow the vocabulary popularized by Gerard Meszaros in xUnit Test Patterns. The distinctions matter because each kind of double lets you check a different thing.
The code in this chapter uses one small interface and one function:
import json
from typing import Protocol
class ChatClient(Protocol):
def complete(self, prompt: str) -> str: ...
def extract_total(client: ChatClient, invoice_text: str) -> float:
reply = client.complete(
f"Return JSON with a 'total' field for this invoice:\n{invoice_text}"
)
data = json.loads(reply)
return float(data["total"])ChatClient is a Protocol, a type that describes a shape. Any object with a complete(prompt) -> str method satisfies it. The next chapter explains why this narrow shape is worth designing deliberately. Here it only gives the doubles something to stand in for.
The five kinds of double
Dummy
A dummy is an object you pass only because a parameter requires one. The code under test never uses it. If anything calls it, the test should fail.
def summarize_if_long(client: ChatClient, text: str, limit: int = 100) -> str:
if len(text) <= limit:
return text
return client.complete(f"Summarize in one sentence:\n{text}")
def test_short_text_skips_the_model():
dummy = object() # has no complete(); any call raises AttributeError
assert summarize_if_long(dummy, "short text") == "short text"This test proves something useful: short input never reaches the model. A dummy is the cheapest way to assert "this path makes no model call".
Stub
A stub returns fixed answers. It controls what the code under test receives, so you can test how your code reacts to that input. It does not check how it was called.
class StubClient:
def __init__(self, reply: str):
self._reply = reply
def complete(self, prompt: str) -> str:
return self._reply
def test_extract_total_parses_reply():
client = StubClient('{"total": 42.5}')
assert extract_total(client, "Total: $42.50") == 42.5The assertion looks only at the return value of extract_total. That is state verification: you check the result and ignore the conversation that produced it. Stubs suit tests of parsing, validation, and formatting code, where the interesting question is "given this reply, what does my code do?"
Spy
A spy is a stub that also records how it was called. The test inspects those records afterward.
class SpyClient:
def __init__(self, reply: str):
self._reply = reply
self.prompts: list[str] = []
def complete(self, prompt: str) -> str:
self.prompts.append(prompt)
return self._reply
def test_prompt_contains_the_invoice_text():
client = SpyClient('{"total": 1}')
extract_total(client, "Total: $42.50")
assert len(client.prompts) == 1
assert "Total: $42.50" in client.prompts[0]In LLM code the spy answers a question a stub cannot: did my code send the right input? A prompt that silently drops the user's text is a real bug, and the model will not tell you about it. It will just answer something plausible.
Mock
A mock is a double with expectations about how it will be called, and the double itself fails the test when those expectations are not met. This is behavior verification: the call is the thing under test.
Python's unittest.mock.Mock is the standard tool:
from unittest.mock import Mock
def test_extract_total_calls_the_model_once():
client = Mock(spec=ChatClient)
client.complete.return_value = '{"total": 42.5}'
extract_total(client, "Total: $42.50")
client.complete.assert_called_once()
prompt = client.complete.call_args.args[0]
assert "Total: $42.50" in promptspec=ChatClient limits the mock to attributes that exist on ChatClient. Without it, a typo such as client.complet(...) would silently create a new attribute and pass.
The word "mock" is overloaded. The Mock class is a tool that can play the stub role (set return_value), the spy role (read call_args), or the mock role (call assert_called_once). Teams often call every double a "mock" because of the library name. When you read a test, ask what it does with the double, not what the double is called.
Fake
A fake is a working but simplified implementation. It has real behavior, just not production behavior. An in-memory database is the classic example. A fake model client contains its own small logic:
class RuleBasedFake:
"""Answers by matching a keyword in the prompt."""
def __init__(self, rules: list[tuple[str, str]]):
self._rules = rules
def complete(self, prompt: str) -> str:
for needle, reply in self._rules:
if needle in prompt:
return reply
raise AssertionError(f"No rule matches this prompt: {prompt!r}")
def test_two_invoices_get_two_different_totals():
client = RuleBasedFake(
[
("ACME", '{"total": 10.0}'),
("Globex", '{"total": 99.0}'),
]
)
assert extract_total(client, "ACME invoice") == 10.0
assert extract_total(client, "Globex invoice") == 99.0A fake can serve many tests with different data, because the data lives in the test and the behavior lives in the fake. It also fails loudly on a prompt it does not recognize, instead of returning a default that hides the problem. The chapter after next builds the most useful kind, a fake that replays scripted replies in order.
Comparing the five
| Double | What it does | What the test checks | LLM example |
|---|---|---|---|
| Dummy | Fills a parameter, never used | That the code does not touch it | `object()` passed on a no-call path |
| Stub | Returns fixed replies | The code's result for that input | Always returns one JSON string |
| Spy | Stub that records calls | What the code sent | Keeps the list of prompts |
| Mock | Has built-in expectations | That specific calls happened | `assert_called_once()` |
| Fake | Simplified working logic | Behavior across many inputs | Keyword rules or an ordered script |
Where each double goes wrong in LLM code
Over-specified mocks
A mock that asserts the exact prompt string breaks whenever someone rewords the prompt, even when the code still works:
client.complete.assert_called_once_with(
"Return JSON with a 'total' field for this invoice:\nTotal: $42.50"
)This test checks wording, not behavior. Assert the parts that matter, such as the invoice text appearing in the prompt, and leave phrasing free to change. Exact-match assertions belong only where the exact text is a contract, for example a system prompt that a compliance review approved.
Patching the SDK instead of your seam
You can use unittest.mock.patch to replace a function deep inside a vendor SDK. This works, but the test then depends on the SDK's internal layout. An SDK upgrade can rename a module and break dozens of tests that have nothing to do with the upgrade. Doubles that implement your own ChatClient interface do not have this problem, which is the argument for the narrow seam in the next chapter.
A double that is easier than the real thing
Every double is a claim about how the real client behaves. A stub that always returns clean JSON claims the model never returns anything else. The real model sometimes wraps JSON in prose, truncates it, or refuses. If your doubles never produce those cases, your tests pass while production fails. A later chapter covers injecting such failures on purpose.
Doubles that drift from reality
A fake or stub written by hand reflects what you believed at the time. If the real API changes its response format, the double keeps passing. Recorded responses and live smoke tests, covered in later chapters, exist to catch this.
Choosing in practice
Start from the question the test asks, not from the tool you know best.
- If the test asks "what does my code do with this reply?", use a stub. Parsing and validation tests are usually stubs.
- If it asks "what did my code send?", use a spy. Prefer a spy over a mock when you want to assert on pieces of the input in ordinary
assertstatements. - If it asks "does my code call the model at all, or exactly once?", a mock's call-count assertions fit well.
- If many tests need different replies, or a test spans several calls, write a fake once and reuse it.
- If the code must never call the model on some path, pass a dummy.
One more distinction affects test quality. State verification (checking results) survives refactoring better than behavior verification (checking calls). If you can express a check as "this input gives this output", prefer that over "this method was called with these arguments". Use call checks for the few cases where the call itself is the requirement, such as "do not call the model for empty input", because each call you pin down is something a refactor can break without changing what users see.
Summary
- A dummy, stub, spy, mock, and fake each answer a different test question. Pick by the question.
- A stub controls input to your code. A spy and a mock check what your code sent. A fake supplies reusable behavior.
unittest.mock.Mockcan play several roles, so judge a test by what it asserts, not by the word "mock".- Doubles encode assumptions, so they can pass while the real API has changed. Later chapters add recordings and live checks to close that gap.
Exercise
A function classify(client, text) calls client.complete(...) and returns "positive" or "negative" based on whether the reply, lowercased, contains the word "positive". You want one test that confirms the reply "Positive!" gives "positive", and a second test that confirms the prompt sent to the model contains the input text. Which kind of double fits each test, and why?
Show answer
The first test needs a stub. It fixes the reply and checks only the function's return value, which is state verification. The second test needs a spy (or a Mock used as a spy). It must record the prompt the code sent so the test can assert that the input text appears in it. A single spy class that returns a fixed reply and records prompts can serve both tests, but the first test should still assert only on the result and the second only on the recorded prompt.
Exercise
A teammate writes client = Mock() with no spec, and the code under test has a typo: it calls client.complet(prompt). The test sets client.complete.return_value = '{"total": 1}' and asserts the function returns 1.0. What happens, and how do you prevent it?
Show answer
Without a spec, the mock invents a complet attribute and returns another Mock object. json.loads then fails on a non-string, so the test fails, but with a confusing error. If the typo only affected an unchecked path, the test could pass wrongly. Create the mock with Mock(spec=ChatClient) so that any attribute not on the interface raises AttributeError immediately. A hand-written stub class has the same protection, because it has no complet method.