Sub topic 1
Why Live LLM Calls Make Bad Unit Tests
Prerequisites
This chapter assumes you can write and run pytest tests, define basic Python classes and exceptions, call an LLM API, parse JSON, and pass dependencies into functions.
A unit test should be fast, repeatable, and focused on your code. A live LLM call violates all three expectations:
- It adds network delay and API cost.
- The model may return different wording or formatting.
- The provider may rate-limit, fail, or change its service.
- A test failure may come from the API instead of your application.
Use live calls in a small smoke test or an evaluation suite. Use a test double for most unit tests.
Fakes, Stubs, and Mocks
A test double is a replacement for a real dependency. The names describe different purposes:
| Double | Main purpose | Typical check |
|---|---|---|
| Stub | Supplies fixed data | Your code handles a known reply |
| Fake | Provides a simple working replacement | Your code follows a realistic interaction |
| Mock | Records expected interactions | The client received a particular request |
For LLM code, a fake that returns scripted replies is often clearer than a mock. It can both return data and record prompts without asserting every internal call.
Put a Narrow Seam Around the Model Client
A seam is a small boundary where production code can receive a replacement dependency. Keep the boundary smaller than the provider's SDK:
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"])The application depends on one method, not on an SDK object. A real client can implement that protocol in production. A fake can implement it in tests.
Build a Scripted Fake Client
Script replies in the order the test needs. Record prompts so the test can verify important input.
class FakeClient:
def __init__(self, replies):
self._replies = list(replies)
self.prompts = []
def complete(self, prompt: str) -> str:
self.prompts.append(prompt)
if not self._replies:
raise AssertionError("No scripted reply remains")
reply = self._replies.pop(0)
if isinstance(reply, Exception):
raise reply
return reply
def test_extract_total():
client = FakeClient(['{"total": 42.5}'])
assert extract_total(client, "Total: $42.50") == 42.5
assert "Total: $42.50" in client.prompts[0]The fake makes the test offline and repeatable. Later tests can script malformed JSON or an exception to exercise parsing and retry paths.
Exercise
Which dependency should a unit test replace: the entire application or the narrow model client?
Show answer
Replace the narrow model client. This keeps the test focused on application behavior while making the external call predictable.