Book Deep-Read · Software Engineering at Google · Chapter 12

Unit Testing

Software Engineering at Google · Ch 12 · Unit Testing · Erik Kuefler · 2020

中文 →

What is this chapter about?

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.

A strange story first

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.

Why the old way hurts

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.

How it works, intuitively

What it buys you

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.

One line to remember

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