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
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…)