use unit tests to chase down bugs

If your unit test coverage was close to 100% – for example, if your code had all been written test-first – you’d have very little problem tracking down bugs. Because the unit tests will tell you most of the places the bug can’t be. But if your coverage is much lower, unit tests can still be a very effective way to track down and isolate problems.

Bugs can often be difficult to track down. They may depend on the interaction between objects in certain states, or they may depend on certain parameters having specific values, or any of a host of other difficult-to-diagnose situations. It’s always tempting to triangulate the bug by adding print statements or by using the debugger, but to my mind that gives no payback. Time spent in the debugger is time that can never be regained. Whereas time spent writing unit tests pays for itself again and again with every build.

So instead of debugging by inspection, I now do it by writing unit tests. If I need to figure out whether an object behaves itself under certain circumstances, I write those circumstances down as examples in a test suite. I find the answer I need, and I also get a set of regression tests for free. So even the code that didn’t contain the bug is now more robust and more understandable. And by writing those tests I’ve also documented the fact that the bug wasn’t there. All this helps speed up the process next time, and improves my overall confidence in my product.

(As usual, none of the above is new. But not everyone has read everything…)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s