Chapter 7. Beautiful Tests
Alberto Savoia
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 if
statement
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
as:
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
increases considerably.
Any nontrivial code, beautiful or not, needs not one, but ...
Get Beautiful Code now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.