Test as Side-effect

I sometimes regard the term "unit test" as unfortunate. It's certainly important that test cases actually certify your code, but in many ways I've come view that as a pleasant side-effect.

For developers unfamiliar with unit testing, the "test" aspect might be a tough sell. After all, they can actually see their code working once they've deployed their application. Indeed, prior to being hired at Spider Strategies, I found I had to disabuse potential employers of the notion that my unit testing experience was solely a function of QA.

For me, the less obvious benefits of unit testing are the more profound. Chief among them, it allows you to be more intimate with your code. One of the essays I enjoy in Getting Real is "Code Speaks". Being metaphor-minded, I savor the conceit of listening to one's code.

Allow me to stretch it to an absurd degree: if you're waiting until you've deployed your application to listen to your code, it's akin to having it shout at you from across the street. It's much better to engage in a conversation with your code when it's sitting nearby. In any good conversation each party can interrupt, correct, and acknowledge. Unit testing provides just that level of intimacy.

If you're coding your test and find yourself having to create a dozen mocks and stubs, your code is telling you it is overly coupled. Once I found myself needing to mock the very class I was testing so that I could simulate a method invocation that took place in the tested method. That was my code telling me it was time to extract class. It has become accepted wisdom that tests should inform one's design, and I'm glad for it. Code that is hard to test is generally accompanied by that foul odor with which we're all familiar.

Do my test cases actually test? I suppose they do, in the end. But much like my IDE, I regard unit testing as a tool that allows easier software development.