A coverage tool hooks into the test run and records which statements were executed and which were not. The output is a percentage and a report: source lines, condition branches, functions. The metric shows which parts of the code the tests did not touch, but it does not say how good the tests are.
How it is counted
The counters are calculated by the tool itself, automatically: developers do not count lines by hand. The typical levels, using JaCoCo as an example:
| Counter | What is counted | What it gives |
|---|---|---|
| Instructions (C0) | executed bytecode instructions | the most precise measure of executed code, independent of source formatting |
| Branches (C1) | outcomes of conditions: if and switch | unexercised behaviour: only one side of a condition was tested |
| Lines | source lines where at least one instruction ran | a clear report directly on the source |
| Methods and classes | executed methods and classes | a rough upper estimate |
Lines and branches are the most common choice. For example, a method where only one side of the condition is tested gives 75% line coverage and only 50% branch coverage:
def discount(total): if total > 1_000: # the test called discount(500) return 10 # this line never ran return 0 # coverage: lines 75%, branches 50%How it is measured
The tool inserts probes into the code: extra instructions that record the fact of execution and do not change the program’s behaviour. This is how JaCoCo works for Java: instrumentation happens on the fly as classes are loaded, probes are placed on the edges of the control-flow graph, and classes grow by about 30% with a time overhead usually under 10%. For Python there is coverage.py, for JavaScript Istanbul and V8 coverage, and for Go the built-in go test -cover command.
How to use it
- Publish a report in CI after every test run: a drop in coverage is a reason to find out what new code is not covered.
- Set a threshold in the pipeline carefully: a hard barrier pushes people to write meaningless tests just for the percentage.
- The report highlights lines and branches that did not run, a hint about where a new test would help most; chasing a formal 100% is not necessary.
100% coverage does not mean the code has been verified: a test without assertions executes lines but catches nothing. Coverage.py also warns that function definitions executed at import time count as covered even if nobody tested the code itself. That is why code coverage is complemented by mutation testing and test design: first decide what to check, and use coverage as an indicator of gaps.
Sources
the term is written from these pagesVerified 9 Nov