Friday, October 5, 2007

Testing from the ground up

Anyone who writes software knows that it's easy to write code rapidly and get something working right away, but the difficult thing is maintaining that code over time as the requirements for what it does and how it does it change. This is where bugs creep into a system and it's up to the programmer and the testing staff to find and remove those bugs. But coders have a tool that they can use called unit testing which allows them to build a testing framework around their code. These unit tests are also code (which makes it a little more fun to write) and is intended to focus on a logical unit of functionality and exercise it in such a way that you feel confident that it's doing what it's supposed to do. As the code changes you always have that suite of tests to run to make sure that it's still doing what it was supposed to do, regardless of how the implementation changes.

At my previous job we spent a fair amount of energy trying to make unit testing a part of our culture, encouraging developers to add unit tests for code when they fix bugs or when they are adding something new. What I found was that it's often pretty difficult or painful to add unit tests to a code base that was built without the idea that it would be tested that way. You would often have to jump through great hoops to try and test something quite simple. This often led to a fair amount of frustration and people would just avoid unit testing at all. One of my past coworkers started a new project of his own and decided to try building unit tests along with the code as it was written. This experience seemed to completely change his mind about the value of unit testing after seeing how valuable it was in creating a project from scratch.

It turns out that, if you have testing in your mind as you develop your software, it naturally gets written in a testable way. And having those tests telling you that everything is okay is incredibly valuable at times. At my current job I am encouraged to build unit tests along with the code that I write and have found that it has been extremely helpful in finding bugs that I would have otherwise missed until a much later date. It's actually pretty easy to write unit tests while you're creating the code, even before you actually write the code. This practice has actually helped fix most of my bugs. By writing a test that shows how the code should work first you then can write the code the way you think it should work and find out if you got it right.