Part 5 of 6 · 3 min read
Tests as feedback
Hard-to-test code points to a design problem.
Test-driven development and design feedback
CC describes three laws of test-driven development (TDD). First, a failing test must exist before any production code is written. Second, the test is only written as far as the point where it fails. Third, the production code is only written as far as the point where that test passes. The cycle lasts seconds, with the tests a step ahead of the code.
TDD is one way to work, and not the only one. Its lasting lesson for design is that code written to be tested has small methods, clear inputs and outputs, and injected dependencies. CC notes that if tests come after the code, the code may turn out hard to test, and some of it may be judged too hard to test at all.
Use difficulty in testing as a signal. A class that needs ten stand-ins has too many dependencies and probably too many jobs (Level 2, module 1). A method that is hard to test without a database probably mixes business rules with storage, and the rules should move into a plain class. A test that must know the internal order of calls is too tied to the code, and a test of the visible result is better.
For concurrent code, CC and JCIP agree that tests are hard and less certain. A passing run does not prove that a race is absent (module 3). Keep concurrent logic small, put as much as possible into plain, single-threaded classes that tests can check, and use stress tests with many threads for the rest.
Keep test code as clean as production code. CC tells a story of a team that allowed messy tests, and found that the tests became a burden and were abandoned. A test suite is useful only while it is trusted and easy to change.
Common mistake
Testing by calling the real clock, database or mail server. The test is slow, fails at random, and may send real mail. Put the dependency behind an interface and use a stand-in.
Interview angle
Answer in your head first, then open it.
How would you test this design?
Name the seams (clock, store, notifier), say which stand-ins you would use, and give two or three tests including a failure case.
What makes code hard to test?
Hidden inputs such as the clock, hidden outputs such as emails, static calls, and objects built inside the method with new.
Fake or mock?
A fake is a small working version. A mock records and checks calls. Fakes keep tests simpler and less tied to the code's internals.
Check yourself: 1. What does a class needing ten stand-ins suggest? 2. Why is a passing concurrency test weaker evidence? 3. What did CC's story show about messy test code?
Words you will meet
| Word | Meaning |
|---|---|
| Seam | A place where an implementation can be swapped for a test |
| Fake | A simple working stand-in for a dependency |
| Test double | Any stand-in used in a test, such as a fake or a recorder |
| Given-when-then | Set up, act, check |
| TDD | Writing a failing test before the code that makes it pass |