One test per behaviour
Not per method
Part five of a series of posts about automated testing.
We are building a self-driving car in Perl. It will pick up jobseekers, and play upbeat music as it drives them to their job interviews. Consider this early code sample:
And a first stab at the tests:
As more functionality gets added, the test becomes harder to read. As more tests accumulate like this, a change to an obscure feature such as the radio can require changes to hundreds of long tests. Instead, aim to write one test per behaviour, not per method:
This produces shorter, more readable tests, which are easier to adapt to new behaviours.
In addition, the tests end up describing the behaviour of the system under test, which can help with understanding unfamiliar code. This relates closely to yesterday’s post about testing reusable interfaces.