I've joined the Anti-IF Campaign

Wednesday, 6 January 2010

Improving TDD with one assertion per test

A nagging problem that I continue to suffer from when practising TDD is the urge to take bigger steps at each turn of the cycle. It's a problematic itch because, when scratched, it leads to longer periods coding with a red bar. In my experience, coding against a red bar is like leaving the lid off a petri dish: bugs grow there. When smaller steps are taken, the lid is off the petri dish for a shorter time and bugs have less opportunity to develop.

Recently, in an effort to address this issue explicitly, I started restricting my unit tests to a single assertion each. It is not an original idea, although I'm not sure where the proper credit for it lies (I first saw it mentioned in this old post by Dave Astels). I've dabbled with the technique before but, for whatever reason, I was unconvinced at the time. However, I've now come to realise that it may be the best weapon I have against the aforementioned itch.

Typically, when I'm writing the test for some planned feature, part of my brain seems to rapidly announce a list of all the conditions that must be tested in order for that feature to be done. Followed to their natural conclusion, these thoughts lead to a unit test that appears comprehensive but looks messy. There are echoes of BDUF here, I think, in the eagerness to get every permutation written down right now, almost OCD-like.

By limiting myself to just one assertion per unit test, I'm forced to ignore all but the simplest of these conditions, which can feel frustrating at first. Yet it has the precise effect of minimising the time spent with a red bar, usually to under a minute. The remaining conditions are dealt with by subsequent unit tests and suddenly I find myself hitting that very tight red-green-refactor rhythm, which tells me that I'm practising TDD how the books say I should.

There is another benefit to using this method too. I've discussed the issue of clean unit tests before and I'm always concerned that my own are not as clean as they should be. With only a single assertion, though, I've thus far found it impossible to write a messy unit test.

0 comments:

Post a Comment