When do unit tests matter? Well for large amounts of production code, they are required or you’ll ship the buggiest code–every new feature or old fix breaks something else and you won’t know it until your manager Bob fires you for shipping the worst possible code. (no offense to any managers named “Bob”, it’s just an example name)
But you are working on a small internal project. The only people that will see it are you, your boss and all three people that need it. You have a short deadline, you don’t have time to fool around. But I’m here to tell you that even then, unit tests are super useful.
I happen to be working on a small internal project–probably only three people will use this little app, so broken windows probably won’t matter, a few minor bugs will be fine, but functionality is still key. I made a really small library of about 3 classes that act as the code-behind(-the-form) but then I decided I needed to change how I was representing key pieces of data to make it a little bigger. That was a painful process that took an entire day, where most of that was running and testing to make sure I didn’t break anything yet (or that I had a to-do list of the things that were still broken).
So this morning I decided I could write unit tests for it. Getting NUnit, figuring out how to write tests with it, finding a quick way to learn about test-driven development and then actually writing 6 key tests took all of about 45 minutes. Those 6 tests replicate a routine test I did yesterday (as described above) that took about 5 or 6 minutes per run.
I didn’t count how many times I manually walked through that test routine yesterday, but it was so tedious that I started delaying testing more and more, so my code became worse and worse, and eventually I was a) having a hard time understanding what was even happening and b) relying on untested code.
After I wrote the tests and.. I didn’t get to run the tests right away because I had to spend a whole 20 long minutes of fixing the worst code I had ever written.
On the other hand, maybe yesterday’s coding failure was due to my lack of caffeine.. I swear I had 3 Mountain Dews! Or was it only 2? Definitely started today off right with 2 cups of coffee and a set of unit tests!