Eclemma says 1 of 4 branches not covered, but whic

2019-04-03 14:00发布

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.

5条回答
做个烂人
2楼-- · 2019-04-03 14:02

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();
}
查看更多
你好瞎i
3楼-- · 2019-04-03 14:06

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

查看更多
Animai°情兽
4楼-- · 2019-04-03 14:16

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

查看更多
Lonely孤独者°
5楼-- · 2019-04-03 14:19

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

查看更多
疯言疯语
6楼-- · 2019-04-03 14:23

What can x and y be?

  • true || true is true (Not covered because of JVM optimization: if the first condition is true, the second won't be evaluated due to short circuit evaluation)
  • false || true is true
  • true || false is true
  • false || false is false
查看更多
登录 后发表回答