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.
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:
This will never allow you to check if
obj
isnull
AND has an error because it will throw a Null Pointer Exception.If code coverage is important, then just use this form:
There is a quite easy woarkaround - just put each logic predicate in separate line, like this:
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
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:
Then look at the output and see what branches you actually hit (e.g.
java ... | grep "BRANCH:" | sort | uniq
). (not terribly satisfying, I know.)There are likely implicit branches either from nested statements within the
if
block or statements from expanding yourx
ory
predicates.Read this: http://emma.sourceforge.net/faq.html#q.fractional.examples
What can
x
andy
be?true || true
is true (Not covered because of JVM optimization: if the first condition istrue
, the second won't be evaluated due to short circuit evaluation)false || true
is truetrue || false
is truefalse || false
is false