Sunday, June 3, 2007

Keeping Unit Tests Small

Unit testing has become one of the mainstays of modern software development. Techniques such as Test Driven Development have delivered significant benefits in ensuring that the developed software is testable.

Designing good tests however seems to be a skill in its own right. I have seem many people struggle to hit the right level. I am not surprised by this - it took me some time to become happy with with my unit tests.

So I thought I would put some time to documenting what I have learnt about writing good unit tests.

  • One test - one feature

  • Keep the environment out of the tests.

One test - one feature

It is very tempting to shore up test code with many assertions. I have found that this makes the tests overly brittle. On failure more diagnosis is required to find
the cause of the problem. With more than one assertion you need more than the test name to find the code causing a problem.

Testing a single feature also makes it easier to name the test - name it after the feature! Not after the method name or class. Grouping the tests together for tests referring to a single class is useful for organisational purposes but beware of reflecting the method names into the tests.

No comments: