Michael Feathers wrote a blog post about the flawed theory behind unit testing some years ago. He concluded that testing does not improve quality just by catching errors. Unit testing and especially Test-Driven Development (TDD) force us to reflect on our code. Thought and reflection are important to improve the quality of our code.
I wrote a component which should generate a higher-level representation of a level in the game engine Unity some weeks ago. Writing the unit tests I noticed that I haven’t thought about an edge case before which required a redesign of the component. Without TDD I most likely wouldn’t have spotted this minor design flaw and the error would have popped up much later when it would have been very hard to find.
I think that there are two main reasons for Unit Testing and TDD:
- It forces us to think about our code.
- Tests provide a safety net for refactorings.
Of course, there are times when unit testing is not appropriate. I don’t like unit testing when I’m still learning the programming platform or the technology. But I think that generally there is no reason why not to write unit tests and why not to write them first.