Unit Testing Old Code

If you are new to unit testing, but the source base is old, the sheer size of code to test will seem daunting. Here are some strategies for adding unit testing to old code.

  • Test code before refactoring or optimizing – The purpose of refactoring and optimizing is to make the code do the exact same thing but in a different way. It is perfectly suited to being unit tested since tests you write at the beginning of the change need to pass at the end.  And, the unit tests will let you make more aggressive changes.
  • Test code while learning what it does – When you’re trying to learn a body of code, a unit test is a good way to check your assumptions about how the code works. This strategy also works well in training a new developer—explain the code by writing new tests for it together.
  • Before fixing a bug, write a failing test – This is the perfect time to add a test since reliably reproducing the bug is a good first step. The beauty of this is that now the bug won’t return.

In general, I would not make a project out of writing unit tests for old code (except during the period where you are installing the xUnit framework and getting used to it). Unit testing works best when it isn’t the end, but instead a means to accomplishing something else.