Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between Line and Branch coverage

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?

like image 292
Gillespie59 Avatar asked Nov 22 '11 15:11

Gillespie59


People also ask

What does line coverage mean?

Definition of Line Coverage Metric The Line Coverage of a program is the number of executed lines divided by the total number of lines. Only lines that contain executable statements are considered, not those with pure declarations.

What does branch coverage mean?

Branch coverage is a testing method, which aims to ensure that each one of the possible branch from each decision point is executed at least once and thereby ensuring that all reachable code is executed.

What is line coverage in unit testing?

Line coverage reports on the execution footprint of testing in terms of which lines of code were executed to complete the test. Edge coverage reports which branches or code decision points were executed to complete the test. They both report a coverage metric, measured as a percentage.


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

like image 94
Kane Avatar answered Sep 23 '22 20:09

Kane