Some thoughts on unit testing

A lot has been said about Test Driven Design (TDD) and unit testing in general. In my opinion it is quite simple:

  1. When you write regular code you usually write some code anyway to exercise it (to see if it’s working properly). Instead of throwing away this code when development is finished, just wrap it in a unit test! It gives you at least a basic coverage and it is not much extra work..
  2. Start at the bottom, test small parts first and then bigger assemblies of small parts. Don’t fall into the trap to depend on external systems (been there, done that). That’s a good signal that the code needs to be refactored! External functionality should be but in a separate interface that can be faked during unit testing (if possible).
  3. Any test you write is better than nothing. So when starting with an existing codebase, just write tests for parts you have to change. In a while the coverage will automatically go up (or maybe help it along by implementing some basic tests).

Don’t be religious about it :)

Interesting book I’m reading right now: Working effectively with legacy code by Michael Feathers