1.3.2 Test behavior, not methods
This brings us to another recommendation when writing tests: your tests should
focus on the behavior they are testing without worrying about which class is under
test. This is why our test names tend to be verbs rather than nouns: we test behavior
(verbs) and not classes (nouns). Still, the difference between behavior and methods
might not be clear: we implement behavior as methods, so testing behavior
must be about test methods. But that’s not entirely true. We do implement behavior
as methods, but the way we choose to implement a certain behavior depends on a
variety of factors, some of which boil down to personal preference. We make a
number of decisions when implementing behavior as methods: their names, their
parameter lists, which methods are public and which are private, the classes on
which we place the methods, and so on—these are some of the ways in which methods
might differ, even though the underlying behavior might be the same. The
implementation can vary in ways that the tests do not need to determine.
Sometimes a single method implements all the required behavior, and in that
case, testing that method directly is all you need. More complex behaviors require
the collaboration of several methods or even objects to implement. If you let your
tests depend too much on the particulars of the implementation, then you create
work for yourself as you try to refactor (improve the design). Furthermore, some
methods merely participate in a particular feature, rather than implement it. Testing
those methods in isolation might be more trouble than it is worth. Doing so
drives up the complexity of your test suite (by using more tests) and makes refactoring
more difficult—and all for perhaps not much gain over testing the behavior
at a slightly higher level. By focusing on testing behavior rather than each
individual method, you can better strike a balance between test coverage and the
freedom you need to support refactoring.