Most programmers have had the experience of looking at a piece of code and thinking it was not only functional but also beautiful. Code is typically considered beautiful if it does what it’s supposed to do with unique elegance and economy.
But what about the tests for that beautiful code—especially the kind of tests that developers write, or should write, while they are working on the code? In this chapter, I am going to focus on tests, because tests can be beautiful themselves. More importantly, they can play a key role in helping you create more beautiful code.
As we will see, a combination of things makes tests beautiful.
Unlike code, I can’t bring myself to consider any
single test beautiful—at least not in the same way I
can look at, say, a sorting routine and call it beautiful. The reason is
that testing, by its very nature, is a combinatorial and
exploratory problem. Every
in the code requires at least two tests (one test for when the condition
evaluates to true and one when it evaluates to false). An
if statement with multiple conditions, such
if ( a || b || c )
could require, in theory, up to eight tests—one for each possible
combination of the values of
a, b, and
c. Throw in control loops, multiple
input parameters, dependencies on external code, different hardware and
software platforms, etc., and the number and types of tests needed
Any nontrivial code, beautiful or not, needs not one, but ...