I am lazy. I don’t mean that I don’t work, I mean that I like to get my work done with as little effort as possible. Writing tests before my code used to look like too much extra work, but I’ve realised just how much time they actually save me.
When you make a small change to something it’s very easy to think to yourself “That’s such a small change, I can’t see how it can possibly fail”, what I have also realised is this really means “Despite this being a small change, it will fail and I can’t possibly see how”.
I recently observed a change to some code that introduced a simple if statement, and all existing tests passed. The problem is that the existing tests only checked the expected behaviour worked (which it still did), but by introducing the “if” statement (and an additional parameter on the method) the developer had changed the expected behaviour under certain circumstances. Thinking it was so simple it couldn’t possibly fail he checked in his changes. I happened to be changing something in the same code and spotted the changes, and realised immediately that his changes would actually result in files being deleted that are still required.
So, how often should you write tests? I think this site sums it up very well