97 Things Every Programmer Should Know

(Chris Devlin) #1

Collective Wisdom from the Experts 191

This implies that what isn’t visible in the test is just as important as what is visible.
Too much code in the test distracts the reader with unimportant trivia. When-
ever possible, hide such trivia behind meaningful method calls—the Extract
Method refactoring is your best friend. And make sure you give each test a
meaningful name that describes the particular usage scenario so the test reader
doesn’t have to reverse-engineer each test to understand what the various sce-
narios are. Between them, the names of the test class and class method should
include at least the starting point and how the software is being invoked. This
allows the test coverage to be verified via a quick scan of the method names. It
can also be useful to include the expected results in the test method names as
long as this doesn’t cause the names to be too long to see or read.

It is also a good idea to test your tests. You can verify that they detect the errors
you think they detect by inserting those errors into the production code (your
own private copy that you’ll throw away, of course). Make sure they report
errors in a helpful and meaningful way. You should also verify that your tests
speak clearly to a person trying to understand your code. The only way to
do this is to have someone who isn’t familiar with your code read your tests
and tell you what she learned. Listen carefully to what she says. If she didn’t
understand something clearly, it probably isn’t because she isn’t very bright. It
is more likely that you weren’t very clear. (Go ahead and reverse the roles by
reading her tests!)

Free download pdf