Sub topic 2
Fakes, Stubs, and Mocks: What Each One Is For
This chapter assumes you can write pytest tests, use Python classes and exceptions, and pass a dependency as an argument. Here you learn the vocabulary for test doubles and which kind suits LLM code.
What a test double is
A test double is an object that stands in for a real dependency during a test. In LLM code the dependency is the model client. A live client is slow, costs money, and returns different text on each run. A double removes those problems.
The three common kinds differ in what they do and what the test checks.
| Kind | What it does | What the test checks |
|---|---|---|
| Stub | Returns fixed answers | The output of your code |
| Fake | Has simple working behavior, such as a scripted queue of replies | The output of your code, and often the inputs it received |
| Mock | Records calls and verifies them against expectations | That specific calls happened |
The names overlap in everyday speech, and libraries blur them. Python's unittest.mock.Mock can act as a stub or a mock depending on how you use it. What matters is the role the object plays in the test.
Stubs: fixed answers
A stub returns the same canned value every time. Use one when the test only needs your code to receive some reply.
class StubClient:
def complete(self, prompt: str) -> str:
return '{"total": 42.5}'A stub is the shortest option. It cannot return a bad reply first and a good one second, so it cannot test a retry. It also does not show what prompt your code sent.
Fakes: simple working behavior
A fake has real logic, but a simplified version. A scripted fake takes a list of replies and returns them in order. It can raise an exception when a scripted item is an error. It can also keep the prompts it received.
class FakeClient:
def __init__(self, replies):
self._replies = list(replies)
self.prompts = []
def complete(self, prompt: str) -> str:
self.prompts.append(prompt)
reply = self._replies.pop(0)
if isinstance(reply, Exception):
raise reply
return replyThis is the main tool for the rest of the tutorial. You can script a malformed reply followed by a valid one. The test then checks the result, and it can also look at prompts to confirm what was sent.
Mocks: verify the interaction
A mock checks how it was used. You set expectations such as "called once with this prompt," and the test fails if the calls differ.
from unittest.mock import Mock
def test_prompt_contains_invoice_text():
client = Mock()
client.complete.return_value = '{"total": 10}'
extract_total(client, "Total: $10")
client.complete.assert_called_once()
sent_prompt = client.complete.call_args.args[0]
assert "Total: $10" in sent_promptThis test is fine for checking that the prompt includes the invoice text. The risk is coupling to implementation details. If you assert the exact prompt wording, any harmless rewrite of the prompt breaks the test. Assert on the parts that matter, such as the input data being present, and not on the whole string.
Which to use
For LLM code, a scripted fake covers most cases. Retries, parsing failures, and API errors all depend on a sequence of replies, and a fake expresses that sequence directly. A fake that records prompts also gives you most of what a mock offers, with plain assertions that are easy to read.
Common errors
- Using a stub for retry logic. The stub returns the same reply each time, so the retry path never sees a different outcome.
- Asserting the full prompt string. The test breaks whenever you edit wording, even when behavior is unchanged.
- Mocking the SDK internals instead of your own client interface. The test then depends on the vendor's structure and breaks on upgrades. The next chapter covers a narrow seam that avoids this.
- Letting a fake silently return something when its script runs out. Raise an error so a test that makes an unexpected extra call fails loudly.
Exercise
You are testing code that retries once when the model returns invalid JSON. The first reply must be "not json" and the second must be '{"total": 5}'. Which kind of double fits, and why does a stub not work?
Show answer
A scripted fake fits, because it returns its replies in order. A stub returns the same value on every call, so it cannot produce a bad reply followed by a good one, and the retry path would never be exercised with a successful second attempt.