Differences between Line and Branch coverage

MavenTestingCoberturaTest Coverage

Maven Problem Overview


I use the Cobertura Maven plugin for one of my project. But I have a question about the generated report:

What is the difference between line and branch coverage?

Maven Solutions


Solution 1 - Maven

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

Solution 2 - Maven

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.

Solution 3 - Maven

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGillespie59View Question on Stackoverflow
Solution 1 - MavenKaneView Answer on Stackoverflow
Solution 2 - MavenTomasz NurkiewiczView Answer on Stackoverflow
Solution 3 - MavenBalaji Boggaram RamanarayanView Answer on Stackoverflow