Differences between Line and Branch coverage

霸气de小男生 提交于 2019-11-29 19:30:12
Kane

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!