Book Deep-Read · Software Engineering at Google · Chapter 13
Software Engineering at Google · Ch 13 · Test Doubles · Andrew Trenk & Dillon Bly · 2020
You click "Pay" in an online store, and somewhere a piece of code asks the bank to charge your card. The engineers who need to check that code can't run a real card charge every time they check it. This chapter is about what to put in place of the things you can't easily bring into a check — and what goes wrong when you overdo it.
Films use stunt doubles: the double does the dangerous jump so the star doesn't have to. Code is the same. Banks, remote servers and databases are slow, expensive and sometimes moody "stars", so during checks you bring in a stand-in. Stand-ins come in roughly three styles:
Without stand-ins, checks talk to real servers: hundreds or thousands of them take hours to run, and fail at random whenever the network hiccups. But once stand-ins became too easy to make, people overused them. Google learned this the hard way: when tools arrived that built a stand-in in one line, everyone treated them as a hammer for every nail. Years later they realised those checks were quick to write, tiring to maintain, and rarely caught real problems — nudge the code's insides and whole rows of them went red.
Pick in the order "real → realistic → scripted → watching moves" and your checks stay fast and steady, without going red every time the internals are rewritten. Google even labels some code "do not make a stand-in for this", pushing people to the real thing or an official realistic version. The honest cost: building a trustworthy realistic stand-in takes real effort, and it has to keep up with the star forever.
Stand-ins are a fallback: use the real thing first, a realistic copy second, and only last a stand-in that reads lines or just records how it was called.
Want the exact difference between fakes, stubs and interaction testing, what a "seam" is, how fast is fast enough for a real implementation, how fakes stay faithful through contract tests, and the only two cases where interaction testing pays off? → Switch to the deep read
You think mocks are standard equipment for unit tests; this chapter says test doubles are a fallback, not a default: prefer the real implementation, use a fake when you can't, stub sparingly, and avoid interaction testing where possible. Google took years and countless tests to learn that mocking frameworks make tests easy to write, costly to keep — and they rarely find bugs.
Part III, "Processes" — the third of four testing chapters. It follows Ch12 Unit Testing (which kept saying "mock less, verify state rather than interactions") and leads into Ch14 Larger Testing (this chapter repeatedly says the risks doubles can't cover must be caught by larger tests with real dependencies). Real-world counterpart: everyday use and misuse of Mockito, googlemock and Python's unittest.mock.
Picture a function that sends a request to an external server and stores the response in a database. A handful of tests like that is doable; hundreds or thousands and the suite runs for hours, turning flaky from random network failures and tests overwriting each other's data. Production code often spans processes and machines, so it naturally doesn't fit the constraints of a small test. A test double is the answer: an object or function that stands in for the real implementation in a test, like a stunt double for an actor.
But doubles bring three complications: testability (the code needs a place to swap in a double, and retrofitting one is expensive), applicability (misused, they make tests brittle and complex, and the loss grows with the codebase) and fidelity (how close the double is to the real thing; a fake database that returns empty for everything is worthless, yet perfect fidelity is often impossible). What happens if you ignore this? Google is its own cautionary tale: mocking frameworks were first treated as a hammer for every nail, and only years later did it become clear that those tests needed constant maintenance while rarely finding bugs.
The book deliberately avoids "mocking" as the umbrella term, because the word means several different things. It names three techniques:
FakeAuthorizationService and later lookups really find it.when(svc.lookupUser(ID)).thenReturn(null) — "when asked about this user, say there's no such user".verify(svc).lookupUser(ID).A mocking framework (Mockito for Java, googlemock for C++, unittest.mock for Python) builds a double in one line, which is why "mock" ends up meaning several things at once. The order of preference is clear: real implementation > fake > stub > interaction testing.
To use a double, the code must let you swap parts. A seam is a way for the system under test to use different dependencies in a test than in production; the most common technique is dependency injection — a class receives its dependencies from outside instead of constructing them with new. PaymentProcessor's constructor accepts a CreditCardService: production passes the real one that talks to an external server, the test passes a double. When hand-written constructors get tedious, Google's Java code commonly uses Guice or Dagger to build object graphs automatically. Dynamic languages like Python and JavaScript can replace individual functions at runtime, so dependency injection matters less there: you can use the real implementation and override just the one or two methods unsuitable for tests.
This is an up-front investment: code written without testing in mind usually has to be refactored or even rewritten before it can get decent tests.
With a real implementation, the test runs all the code in the dependency — closer to production, more confidence; lean too hard on doubles and you need integration tests or manual checks to get the same confidence, which get skipped when they're slow. Deeper still: replacing every dependency of a class with doubles arbitrarily draws the test boundary around whatever code the author happened to put in that class, whereas a good test depends only on the API under test, not on how the implementation is split up. If a bug in the real implementation fails your test — that's good: production would break too; when a cascade fails, CI finds the culprit change.
Preferring real implementations is called classical testing; preferring mocking frameworks is mockist testing. Google found the latter hard to scale: it demands strict guidelines when designing the system under test, and most engineers' default style suits classical testing better.
Case study: @DoNotMock. Google ships a @DoNotMock annotation in the Error Prone static analysis tool, letting API owners declare "don't mock this type, better alternatives exist". Try to build one with a mocking framework and you get an error pointing you to a real implementation or a fake. It's used most for value objects simple enough to use as-is and APIs with well-engineered fakes. Why does the owner care? Every stub or interaction test duplicates the API's behavior; when the owner wants to change it, they may find it mocked thousands or tens of thousands of times, many of those violating the contract (returning null from a method that never returns null).
When a real implementation is good enough: fast, deterministic, simple dependencies — all three, and use the real thing. Value objects (money, dates, addresses, lists and maps) always stay real. For complex code, weigh three dimensions:
new Foo(new A(new B(new C()), new D()), new E(), …, new Z()) is hard to write and breaks whenever a constructor changes, while @Mock Foo mockFoo; is one line and very tempting. The book's ideal: reuse production's object-construction code (factory methods or automated DI), provided it's flexible enough to accept doubles.A fake behaves so much like the real implementation that the system under test can't tell which one it's talking to. The book's FakeFileSystem keeps an in-memory map from file name to contents — and since the real implementation throws FileNotFoundException for a missing file, the fake must too. In organisations where fakes are rare, engineers either suffer slow, flaky real implementations or fall back to stubs and interaction tests.
Who writes it, and where: a fake takes domain knowledge and must change whenever the real implementation does, so the team that owns the real implementation should write and maintain it. With a handful of users it may not pay off; with hundreds it clearly does. Build one only at the root of the code that can't be used in tests — fake the database API, not every class that calls it. For a service with client libraries in several languages, you can write a single fake service and point every client at it: crossing processes is heavier, but fine as long as tests stay fast.
Fidelity is the central concept. A fake needn't be faithful on disk storage, latency or resource use (to test performance you need the real thing), but it must be faithful to the API contract: same input, same output, same state change — if the real database.save(itemId) errors on a duplicate ID, so must the fake. As the book puts it: perfect fidelity to the real implementation, but only from the test's perspective. A fake hashing API needn't produce the same hash values as the real one, as long as the contract promises no specific values and each input maps to a unique result. Rare edge paths can be left unimplemented, but should fail fast, telling the engineer "the fake doesn't apply here".
A fake must have its own tests, or it will silently drift as the real implementation evolves. The approach is contract tests: one suite written against the API's public interface, run against both the real implementation and the fake. The run against the real one is slower, but only the fake's owners need to run it.
If no fake exists: first ask the API owners to build one; failing that, wrap your calls to the API in a single class and write a fake of that class, covering only the subset you use (some Google teams contributed such fakes back to the owners). A fake can also be seen as an optimisation: if the speedup doesn't outweigh the cost, stay with the real implementation.
Stubs are quick, so it's tempting to stub whenever the real implementation is awkward. The book lists three sins. Unclear: extra stubbing code dilutes the test's intent and is hard to follow without knowing the implementation; if you have to step through the system under test in your head to see why certain functions are stubbed, stubbing is the wrong tool. Brittle: stubs leak implementation details into the test, so implementation changes force test changes. Less effective: when(calc.add(1, 2)).thenReturn(3) hand-copies part of a contract into the test with no guarantee it's right; and stubs hold no state, so after save(item) you can't get(item.id()).
The book's counter-example stubs five functions (server available, begin transaction, init, pay, end transaction) and can only end with verify(server).pay(…), because there's no way to know whether money moved. With a fake credit card server, the test shrinks to "call → assert getMostRecentCharge(card) equals 500".
When stubbing fits: when you need a function to return a specific value to put the system under test into a certain state (e.g. return three transactions to test a counter), and to simulate errors that a real implementation or fake can hardly trigger. The rule: every stubbed function should relate directly to the test's assertions, so a test stubs only a few; needing many is a sign of overuse, or of a system under test that's too complex and should be refactored. Even then, real implementations or fakes are still better.
The book contrasts two sorting tests. The state test calls sortNumbers([3,1,2]) and asserts the result is [1,2,3] — quicksort or bubble sort, who cares. The interaction test only does verify(mockQuicksort).sort(…), and can't possibly know whether the numbers got sorted, because the double can't sort. That's the core problem: interaction testing only checks that a function was called as expected and then assumes "if save was called, the item was saved"; state testing actually verifies that assumption. It also bakes "which function the system calls" into the test; some at Google jokingly call such tests change-detector tests — they fail on any production change, even when behavior stays the same.
Interaction testing is warranted in only two cases: first, you can't do state testing — the real implementation is too slow and no fake exists, so verifying calls gives at least basic confidence; second, the number or order of calls is itself the behavior — a cache should cut database calls, so assert verify(db, atMostOnce()).selectRecords(). State verification you can't do in a unit test belongs in an integration test against a real database.
Two best practices. Verify only state-changing functions: sendEmail(), saveRecord(), logAccess() have side effects and are worth verifying; read-only calls like getUser() or readFile() return values the system uses for other work you can already assert, so verifying them is redundant and brittle. Avoid overspecification: to test "the greeting includes the user's name", check only the relevant argument with setText(eq("Fake User"), any(), any()) rather than pinning greeting, version and icon, and split different behaviors into separate tests.
Table 1 · Four options and their honest costs
| Option | Fidelity | Catches real bugs | Maintenance cost | Use when |
|---|---|---|---|---|
| Real impl | Highest | Strong, even bugs in dependencies | Building the dependency tree; may be slow or nondeterministic | Fast, deterministic, simple deps; always for value objects |
| Fake | High at the contract level | Strong | Writing it, tracking the real one, contract tests — borne by the owner | Real impl slow or non-hermetic, and many users |
| Stub | Only a few hand-copied returns | Weak; a wrong copy goes unnoticed | Leaks internals; hard to read with many stubs | Driving into a specific state, simulating rare errors |
| Interaction test | Doesn't run the impl | Weakest; only "it was called" | Change detector — any change turns it red | State testing impossible, or call count / order is the behavior |
Table 2 · Real implementation or double: judging three dimensions
| Dimension | Leans real | Leans double | The book's advice |
|---|---|---|---|
| Execution time | ~1 ms extra per case; few cases | ~1 s extra per case × hundreds of cases | Start real, switch when slow; parallelism and build caching buy time |
| Determinism | Occasional flakes | Frequently flaky; depends on outside services or the clock | Use a double, or a hermetic instance the test controls |
| Construction | Can reuse production factories / DI | Hand-building the whole tree | Don't grab the one-line @Mock; make construction reusable first |
This isn't a "fewer doubles is always better" dogma: the book keeps saying there's no exact answer, and fakes cost something too. But the default sits at the real-implementation end, and departing from it needs a reason.
At Google's scale, a type mocked tens of thousands of times becomes impossible for its owner to change, while one good fake can be shared by thousands of tests. Double strategy isn't personal testing style; it's part of an API's ability to evolve. Asked in an interview "how do you mock dependencies?", the best answer starts with whether you need to mock at all.
Industry evidence · public record
① Doubles fix slow, costly, nondeterministic dependencies, but cost you testability, applicability and fidelity.
② Three techniques: fakes (lightweight working implementations), stubs (hard-coded returns), interaction testing (verify calls only); don't lump them as "mocking".
③ Seams come from dependency injection; testability is an up-front investment that gets pricier the later you make it.
④ Prefer the real implementation: fast, deterministic, simple deps means real, and value objects are always real; a real bug turning your test red is a good thing.
⑤ Three dimensions: execution time (start real, switch when slow), determinism (non-hermetic → double or hermetic instance), construction (reuse production factories / DI).
⑥ If the real thing won't do, use a fake: written by the owner, built at the root, faithful to the contract from the test's view, failing fast when unsupported, kept honest by contract tests.
⑦ Stubbing's three sins: unclear, brittle, less effective; use it to drive state or simulate errors, with every stub tied directly to an assertion.
⑧ Avoid interaction testing: only when state testing is impossible or call count / order is the behavior; verify only side-effecting calls, never overspecify.
⑨ The @DoNotMock lesson: an API mocked tens of thousands of times can't change; your double strategy decides how your API evolves.