Book Deep-Read · Software Engineering at Google · Chapter 12
Software Engineering at Google · Ch 12 · Unit Testing · Erik Kuefler · 2020
The previous chapter said automated checks let many people safely change the same program every day. This one goes a level down: the kind of check Google engineers write most — the unit test, which checks one small piece of code — and how to write it so it helps instead of getting in the way.
You'd think more tests always means more safety. The chapter opens with a counterexample. An engineer, Mary, adds a couple dozen lines of code and gets a screen full of failures when she tries to check in. She spends the whole day going through them and finds not a single real problem: the tests had memorized what the program's internal parts looked like, she moved a few parts around, and everything went red. Tests meant to save her time ate days of it.
Bad tests have two diseases. They are brittle: a harmless change unrelated to any real problem makes them fail. And they are unclear: when they fail, nobody can tell what they were checking or how to fix them. At Google one engineer may run thousands of tests in a day, and a single company-wide change can trigger hundreds of thousands. Even if only a small share cry wolf, the wasted time is enormous.
Written this way, a test rarely needs touching again: cleaning up the inside, adding features, or fixing bugs shouldn't change it. Only when the program's promised behavior really changes should the test change too. Google says tests that follow these rules are orders of magnitude more valuable than ones that don't. The honest cost: they take more thought up front — you have to ask how a real user would call the code — and you must tolerate some repetition.
A good unit test only raises the alarm when something is truly broken — and when it does, you can see what broke.
Want to see which three of the four kinds of change should never touch a test, how state and interaction testing differ, how to lay out given/when/then, and why tests should be DAMP rather than DRY? → Switch to the deep read
You'd think the more unit tests the better; this chapter says maintainability is what makes or breaks them — a good test, once written, should never need to change, and should fail only for real bugs, with an obvious cause. The practices fall into two groups: avoid brittleness (test via public APIs, verify state rather than interactions) and achieve clarity (test behaviors rather than methods, no logic in tests, readable failure messages, DAMP over DRY).
@Before.Part III, "Processes", second of the four testing chapters. It builds on Ch11 Testing Overview (the size and scope axes) and leads into Ch13 Test Doubles (this chapter keeps saying "mock less"; the next one explains when not to) and Ch14 Larger Testing. Real-world counterpart: everyday unit testing in JUnit, Truth, and Go's testing package.
Unit tests are the tests Google writes most. The rule of thumb here is about 80% unit tests and 20% broader-scoped tests (Chapter 11 splits the latter into 15% integration and 5% end-to-end). An engineer runs thousands of unit tests directly or indirectly on an average workday, and a single large-scale change can trigger hundreds of thousands of tests. Unit tests pay off because they are small, fast, and deterministic, easy to write alongside the code, make high coverage cheap, are easy to diagnose, and double as usage examples.
But volume magnifies their maintenance cost too. Mary's story makes the point: a few dozen lines of feature, a screen of failures, none of them a real bug — just tests whose assumptions about internal structure had been broken. She couldn't tell what they were trying to do, and the hacks she added made them harder to understand next time. The tests drained productivity without improving quality. The book names two causes: brittle tests, which break on harmless, unrelated changes, and unclear tests, which make it hard to tell what's wrong, how to fix it, and what they were for. Left alone? As the book puts it, if every change requires engineers to hand-tweak the tests, calling it an "automated test suite" is a bit of a stretch.
The book first asks: once a test is written, how often should we expect to change it? The answer depends on which of four kinds of change is being made to production code:
The book's framing is precise: changing a test for a behavior change means you are breaking an explicit contract; changing one in the other three cases means you broke an unintended contract. With this rule, growing a system means writing a few new tests, not touching every old one — which matters especially at Google, where many refactorings are done through large-scale changes.
The single most important defense against brittleness: invoke the system under test the way its users would, through its public API, not its implementation details. The book's example is a transaction processor: a public processTransaction, with a private isValid (amount below balance) and saveToDatabase (serializes the record as "me,you,100"). The tempting shortcut strips private and tests both methods directly, asserting on the stored string. Rename a method, move it into a helper class, change the serialization format — the tests break, and real users never notice.
The better version uses only public methods: give "me" a balance of 150 and "you" 20, transfer 100, assert the balances are 50 and 120; add another test where an insufficient balance leaves both unchanged. Same coverage, but now the test is a contract: if it breaks, an existing user would break too (a footnote calls this the "use the front door first" principle).
The hard part is that "public" is not the language's public: here the public API means what the unit exposes to third parties outside the owning team. A Java class declared public for access across packages may not count; Python has no visibility, only an underscore convention; and Bazel can further restrict who may depend on what. The book's rules of thumb: a helper class serving only one or two classes is not its own unit — test it through them; a package or class anyone can use without consulting its owners is almost certainly a unit — test it directly; a support library usable only by its owners but offering general functionality is also a unit — test it directly too, accepting some redundant coverage that guards against a gap if one of its users is ever deleted.
The second way tests lean on implementation details is not in what they call but in how they verify. State testing observes the system itself after invoking it; interaction testing checks that the system made an expected sequence of calls on its collaborators. The latter is more brittle for the same reason testing a private method is: it checks how the system arrived at its result, when usually you only care what the result is.
The book's counterexample: createUser("foobar") followed by verify(database).put("foobar"). It can go wrong both ways. If a bug deletes the record right after writing it, the test still passes. If a refactoring switches to a slightly different but equivalent write API, the test fails. Replace it with assertThat(accounts.getUser("foobar")).isNotNull(), which states what we actually care about. The most common source of bad interaction tests is over-reliance on mocking frameworks, so Google prefers real objects over mocks whenever the real ones are fast and deterministic.
Failures are inevitable, and they are good — they are how a unit test delivers value. A test fails for one of two reasons: the system has a problem, or the test does. How fast an engineer can tell which depends on the test's clarity. Tests often outlive their authors; unclear production code can be decoded by seeing what calls it, but the worst case for an unclear test is that it gets deleted — which suggests it may have provided zero value for years.
Engineers' first instinct is one test method per production method. The book's counterexample, testDisplayTransactionResults, asserts both "You bought a ..." and the low-balance warning — likely because someone piled the second assertion onto the old test when the message was added, violating "unchanging tests" and letting the test grow with the method. Better: one test per behavior. A behavior is a guarantee a system makes about how it will respond to a series of inputs while in a particular state, often expressible as given / when / then: "Given an empty account, when attempting to withdraw, then the transaction is rejected." Methods and behaviors are many-to-many: most nontrivial methods implement several behaviors, and some behaviors need several methods.
Three writing rules follow. Structure: separate the given / when / then blocks with whitespace or comments (also known as arrange / act / assert), so a reader can read at three levels — name, then comments, then code. The usual violation is interleaving assertions between calls. Multistep flows may alternate when / then, but the vast majority of unit tests need one of each. Naming: the test name is often the first or only thing visible in a failure report, so state the action and the expected outcome, e.g. divide_byZero_throwsException. That's wordier than production code, but nobody calls these names; humans read them. If stuck, start with "should" and read it with the class name: "BankAccount should not allow withdrawals when balance is empty." If a name needs "and", you are probably testing two behaviors.
A clear test is trivially correct upon inspection. That's achievable because each test handles one specific set of inputs, while production code must generalize. Production code has tests guarding its complex logic; test code has nothing — if you feel you need a test for your test, something has gone wrong. Logic means operators, loops, conditionals. The book's example has just one string concatenation, baseUrl + "/albums", where baseUrl already ends in a slash; spell out the expected value and the bug jumps out: photos.google.com//albums — and if production code made the same mistake, the original test would never catch it.
Ideally a failure message lets you diagnose without opening the test: expected outcome, actual outcome, relevant parameters. "Test failed: account is closed" is bad (was it expected to be closed, or not?); "Expected an account in state CLOSED, but got account: {name: "my-account", state: "OPEN"}" is good. Libraries help: JUnit's assertTrue(colors.contains("orange")) only sees a boolean and can say only "expected true but was false"; Google's Truth, assertThat(colors).contains("orange"), can say "[red, green, blue] should have contained orange". Without such a library, write it by hand, as in Go's convention Add(2, 3) = %v, want %v.
Production code follows DRY: change one place, at the cost of readers following chains of references. The math differs in tests. Good tests are meant to be stable, and you want them to break when the system changes, so DRY's "easy to change" benefit shrinks; meanwhile complexity costs more, since tests have no tests of their own. So tests should aim for DAMP — Descriptive And Meaningful Phrases: some duplication is fine if it makes the test simpler and clearer. The book's counterexample hides user creation, registration, and validation inside helpers full of loops and ternaries — test bodies are concise but incomplete, and the helpers hide a bug. DAMP complements DRY rather than replacing it: factor things out to make tests more descriptive, not merely less repetitive.
For the three common forms of sharing: shared constants like ACCOUNT_1 hide why a value was chosen and tempt reuse where they don't quite fit — use construction helpers with sensible defaults so each test states only the fields it cares about (Java emulates named parameters with a Builder; a footnote suggests slightly randomizing defaults so nobody quietly depends on them). Shared setup is best for constructing the object under test and its collaborators; if a test depends on a specific value from setup (the hard-coded "Donald Knuth"), it should override that value in its own body. Shared validation: a big validate() at the end of every test is a bad habit — intent disappears, and one bug turns a swath of tests red; a good validation helper asserts a single conceptual fact, such as "this user has access to this account", hiding the loop it needs. Test infrastructure shared across suites is more like production code — many callers, hard to change — so treat it as its own product with its own tests.
Table 1 · Avoiding brittleness: two choices, two kinds of error
| Choice | On a behavior-preserving refactor | On a real bug | Honest cost |
|---|---|---|---|
| Via public API | Stays green | Fails on user-visible bugs | Must think through unit boundaries; support libraries get redundant coverage |
| Private / implementation | Breaks (rename, split, reformat) | Catches only what it stares at | Cheapest to write, costliest to maintain |
| Verify state | Stays green | Fails if the result is wrong | Needs a way to read state back; real deps must be fast and deterministic |
| Verify interactions (mock verify) | Breaks (equivalent API swap) | May miss it (written then deleted) | Worth it only when the call itself is the behavior |
Table 2 · Sharing test code: when and how to extract
| Technique | Good use | Bad use | Litmus test |
|---|---|---|---|
| Shared constants | Rarely; when the value doesn't matter | ACCOUNT_1 reused hundreds of lines away | Does the reader have to scroll up? |
| Construction helpers | Defaults + override only what matters | Tests silently depend on defaults | Values that matter live in the test body |
| Shared setup | Build the SUT and collaborators | Tests depend on setup's specific values | If you depend on it, override it explicitly |
| Validation helpers | Assert one conceptual fact | A catch-all validate() | Would one bug turn a swath red? |
| Test infrastructure | Treated as a product, with its own tests | Ad-hoc per team, unowned | Standardize early on shared libraries |
The overarching criterion is the book's own: a test's body should contain all the information needed to understand it, and nothing irrelevant or distracting (complete and concise). The two choices in Table 1 reinforce each other: tests that go through the public API and verify state are also the easiest to write as one test per behavior. Interaction verification isn't banned — Chapter 13 covers its legitimate uses — but it should be the exception, not a default that comes free with a mocking framework.
The scale context: thousands of unit tests per engineer per day, hundreds of thousands triggered by one large-scale change. At that volume even a small share of brittle tests taxes every repository-wide change — whether tests stay unchanged decides whether big refactorings are feasible at all. Asked in an interview how to write good unit tests, the strong answer isn't a coverage number; it's this chapter's TL;DR list.
Industry evidence · public record
YourFunc(%v) = %v, want %v rather than just got %v, want %v, with the actual value printed before the expected one. google/styleguide · Go Style Decisions ↗verify-style assertions both cry wolf and miss real bugs.① Maintainability is the crux: a good unit test never changes once written, and fails only for real bugs with an obvious cause.
② Two diseases: brittle (breaks on harmless changes) and unclear (can't tell why it failed); both cost more at scale.
③ Of four kinds of change, only behavior changes should edit old tests; editing them for refactors, features, or bug fixes signals brittleness.
④ Test via public APIs: test fails ⇔ a user would fail; "public" means usable by third parties, not the public keyword.
⑤ Test state, not interactions: verify(db).put can pass on a bug and fail on a harmless refactor; use real objects when you can.
⑥ Test behaviors, not methods: given / when / then, one behavior per test; an "and" in the name means split it.
⑦ No logic in tests: a single string concatenation can hide a double-slash bug.
⑧ Failure messages state expected, actual, and inputs; Truth and Go's want convention are ready-made tools.
⑨ DAMP, not DRY: construction helpers with defaults, setup that only builds objects, validation helpers that assert one fact, and test infrastructure with its own tests.