5.3. Code Coverage

Code coverage, in the simplest possible terms, means how much of your code is actually executed by your tests. Code coverage analysis is the art of figuring that out.

Figuring out how much of your code is being covered by your tests is a key part of your testing strategy. It's not the most important part, or the least. After all, it's just a number. But it is a number that can help you figure out where to spend your testing resources, how much work you have left to do in terms of writing your tests, and where you might be writing too much code.

It is also a number that cannot stand on its own. You have to combine code coverage analysis with other metrics such as code complexity, test results, and plenty of common sense.

5.3.1. Why Measure Code Coverage

Code coverage is important for a couple of key reasons:

  • If parts of your code aren't being covered by your tests, this may mean that there are bugs waiting to be found by your customers.

  • If parts of your code aren't being covered by your tests, you might not actually need that code.

In a perfect world, you would write tests that exercised every line of code you ever wrote. Every line of code that doesn't get run by a test could be a defect waiting to appear later on, possibly after your software is in the hands of customers. As I said before, the earlier in the cycle you find a bug, the cheaper it is to fix and the less impact it has. So achieving a high level of code coverage as early as possible in your project ...

Get Code Leader: Using People, Tools, and Processes to Build Successful Software now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.