CARVIEW |
Navigation Menu
-
Notifications
You must be signed in to change notification settings - Fork 277
Line Coverage Explained
WIP: Please understand that this page is still a work in progress.
There have been a lot of concerns about how the way cobertura handles things like switch, if, while, etc. statements. This wiki is designed to explain the branch coverage that cobertura uses on certain statements. NOTE: These are subject to change and an update to this wiki page will be provided. Please understand that the jdk team could at any time alter the byte code so certain statements work more efficiently which could alter the code coverage percentages.
Example Source Code:
if (x == 0) {
System.out.println("X is zero");
} else {
System.out.println("X is invalid");
}
-
If the value of x is equal to 0, then this will be the branch coverage:
-
If the value of x is not equal to 0, then this will be the branch coverage:
-
If this code is executed two times, the initial value of x is equal to 0 and another value not equal to 0, then this will be the branch coverage:
So as you can tell, the only way to get "Complete" or "Full" code coverage with the if statement is to execute the if statement twice. Once for the if statement to be true and the other to be false.
if (x == 0) {
System.out.println("X is zero");
} else if (x == -1) {
System.out.println("X is negative one");
} else {
System.out.println("X is invalid");
}
- In the situtation above, let us say we pass in a value of 0 the first time and 1 the second time. This is the coverage:
As you can tell the middle if statement gets executed, however it has a red marker because the if statement never is -1.
if (x == 0) System.out.println("X is zero");
- Let us say you pass in a value of 1. This is the coverage:
boolean isZero = (x == 0) ? true : false;
- This is similar to how the single line if statement works in scenario 3. Let us say we pass in a value of 1. This is the coverage:
if (x != 0 && y != 1) {
System.out.println("X is not 0 and Y is not 1.");
} else {
System.out.println("X is 0 and Y is 1.");
}
if (x == 0 || x == 1) {
System.out.println("X is either 0 or 1.");
} else {
System.out.println("X is not either 0 or 1.");
}
int x = 0;
while(x != 5) {
x++;
}
int x = 0;
do{
x++;
}while(x != 5);
for (int x = 0; x < 5; x++) {
System.out.println(x);
}
A for-each loop iterates though each element in a list. Let us say we have this example:
List<String> x = new ArrayList<String>();
x.add("Hello");
x.add("World");
for(String element : x ) {
System.out.println(element);
}
Info: The way this type of loop is pronounced is "For each String in x".