Differences between Line and Branch coverage
Asked Answered
I

3

124

What is the difference between line and branch coverage in Cobertura Maven?

Introspect answered 22/11, 2011 at 15:24 Comment(0)
R
246

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

Retsina answered 22/11, 2011 at 15:56 Comment(4)
Great answer! It shows when line coverage gives false feeling of having good code!Superhighway
what are the possible bugs you can get due to line coverage or branch coverage ?Phobe
is there a good use for line coverage that branch coverage doesn't satisfy?Whitewash
@bluenote10 No, because branches not taken will contain statements, which will cause statement coverage to be less than 100%.Retsina
D
70

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.

Deli answered 22/11, 2011 at 15:27 Comment(0)
K
3
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.

Kamilah answered 19/4, 2013 at 18:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.