Is there a simple way to tell which branch I am missing? I.e. I have some code like this:
if (x || y) {
// do stuff
}
In the coverage highlighting there is a yellow dot in Eclipse that says:
1 of 4 branches missed
but I would like to know which branch is missing.
An open issue on the github repo for Eclemma's parent, jacoco, suggests that such a feature would actually be a bit difficult to include.
However, even without an Eclemma feature, if the goal is just to figure out the branches missed in a specific case, you could instrument your code to keep track. The simplest example is old fashioned print statements:
if (x || y) {
System.out.println("BRANCH: " + x + ", " + y);
// Do stuff
}
Then look at the output and see what branches you actually hit (e.g. java ... | grep "BRANCH:" | sort | uniq
). (not terribly satisfying, I know.)
The answer is true|| true
was not covered.
This is because once the JVM has found the first condition to be true, then it won't run the second condition (it's optimized) which means that portion of the code is never run.
As Maroun said, 3 out of 4 branches will allow the conditional to pass. If you're still worried about code coverage, you can refactor the conditional to be a &&
instead of a ||
.
(x || y)
is the same as (!(!x && !y))
and this will allow you to test all conditions since there are only three branches now.
The original form of the conditional is often seen in guard statements:
if (obj == null || obj.hasError())
{
throw new RuntimeException();
}
This will never allow you to check if obj
is null
AND has an error because it will throw a Null Pointer Exception.
If code coverage is important, then just use this form:
if (!(obj != null && !obj.hasError()))
{
throw new RuntimeException();
}
There is a quite easy woarkaround - just put each logic predicate in separate line, like this:
if (x
|| y) {
System.out.println("BRANCH: " + x + ", " + y);
// Do stuff
}
Now when you'll run analisys, the marker should point directly on branch that is missed. After you'll cover it up, you can reformat your code the right way.
HTH
There are likely implicit branches either from nested statements within the if
block or statements from expanding your x
or y
predicates.
Read this:
http://emma.sourceforge.net/faq.html#q.fractional.examples