What is the difference between line and branch coverage in Cobertura Maven?
3 Answers
Line coverage measures how many statements you took (a statement is usually a line of code, not including comments, conditionals, etc). Branch coverages checks if you took the true and false branch for each conditional (if, while, for). You'll have twice as many branches as conditionals.
Why do you care? Consider the example:
public int getNameLength(boolean isCoolUser) {
User user = null;
if (isCoolUser) {
user = new John();
}
return user.getName().length();
}
If you call this method with isCoolUser
set to true
, you get 100% statement coverage. Sounds good? NOPE, there's going to be a null pointer if you call with false
. However, you have 50% branch coverage in the first case, so you can see there is something missing in your testing (and often, in your code).
-
14Great answer! It shows when line coverage gives false feeling of having good code!– MAGx2Jan 29, 2014 at 16:37
-
what are the possible bugs you can get due to line coverage or branch coverage ? May 22, 2020 at 0:38
-
is there a good use for line coverage that branch coverage doesn't satisfy? Feb 24, 2022 at 18:12
-
@bluenote10 No, because branches not taken will contain statements, which will cause statement coverage to be less than 100%.– KaneMay 2, 2022 at 14:26
Take this code as a simplified example:
if(cond) {
line1();
line2();
line3();
line4();
} else {
line5();
}
If your test only exercises the cond
being true and never runs the else
branch you have:
- 4 out of 5 lines covered
- 1 out of 2 branches covered
Also Cobertura report itself introduces some nice pop-up help tooltips when column header is clicked:
Line Coverage - The percent of lines executed by this test run.
Branch Coverage - The percent of branches executed by this test run.
if(cond){
//branch 1
}else{
//branch 2
}
You need to address all lines is branch 1 and branch 2 to get 100% coverage for both LineCoverage and BranchCoverage.
If you at all miss anything in else, you will get half of branch coverage. If you have missed anything in # of lines in both if and else, you will get BranchCoverage of 100% but not 100% with line coverage.
Hope this helps.