Unit tests - documentation you can compile

In the category of best practices I have to include my thoughts today on unit tests as a form of "comments/documentation you can compile". Let me explain:

I recently had the experience of (a) working on a small but complicated software development project, (b) leaving that project for six months, and then (c) being asked to work on it again. All I can say it wow -- what a great experience it was to come back to a project that was loaded with unit and code coverage tests.

I don't say that to toot my own horn -- I say it because I really see what a great form of "live" documentation unit tests can be for a software development project. Even looking at my own code months later I sometimes wondered "Hmm, I wonder what the heck I was thinking here?" Then I looked at the tests and thought, "Oh, that's right, the customer said they wanted XYZ, so I took that approach." Live, running, documentation -- wow.

The initial setup

All I did six months ago was use JUnit for the unit tests, Cobertura for the code coverage analysis, and Ant to build it all reliably. That's it. It wasn't that hard, it didn't take long at all to set everything up, but man, was it worth every ounce of energy -- especially when I had to come back to the project and switch some of the code from using Axis2 web services to using Apache CXF.

(BTW, if you need an Ant build script to start working with, I have this sample Ant build script that works with Junit and Cobertura.)

In short, unit tests are good because you know that some portion of your code has been tested, and code coverage tools are good because they show you which lines of code those unit tests are covering.

Unit tests as documentation

Again, what really hit me on this project is that my old unit tests really are live documentation for what I was thinking when I left the project. By their very nature unit tests imply how you intended your code to be used, and in all likelihood, how you intended classes and methods not to be used.

So, create unit tests -- at the very least for the hardest portions of your code -- and keep them running throughout the life of your project. You'll have some great built-in documentation, and unlike those other pesky little comments, unit tests will break when you change your business logic. That's why I refer to it as "live documentation". Maybe it would be better to call it "documentation you can compile" or "comments you can compile"?