Chapter 88. Use Coverage to Improve Your Unit Tests
Emily Bache
Measuring the coverage of your tests is easier than ever. In a modern IDE, the button to run your tests with coverage is right next to the ones to run or debug them. The coverage results are presented class by class with little chart graphics, as well as relevant lines being highlighted in color in the source code.
Coverage data is easy to get hold of. What is the best way to use it, though?
When You’re Writing New Code
Most people agree that you should deliver unit tests together with all the code you write. You can argue about which order to do things in, but in my experience, what works best is short feedback loops. Write a little test code, write a little production code, and build up the functionality together with the tests. When I’m working like this, I will run the tests with coverage from time to time as additional insurance that I haven’t forgotten to test some new code I’ve just written.
The main danger here is that you become very satisfied with a high coverage number and don’t notice you’re missing both code and tests for a crucial piece of functionality. Perhaps you forgot to add error handling. Perhaps you missed out on a business rule. If you never wrote the production code in the first place, then coverage measurements can’t discover that for you.