Eclemma: branches missed in a for-loop -- what does it mean?

5.2k views Asked by At

Testing my code I've encountered a thing that I can't interpret. Examining the code coverage with eclemma I've found a header of a for-loop that is highlighted in yellow with the message reading "1 of 2 branches missing".

The code line is as following:

    for (int i = maxIdx; i >= 0; i--) {

The body of the loop is highlighted as covered (and is actually executed), as well as the preceding and following statements, and the method works fine under all possible conditions. The headers of other for-loops, as far as I could notice, are highlighted in yellow with the same message only in cases if the body of the loop have never executed.

What is the sense of this message? What branch is missing?

2

There are 2 answers

1
Godin On BEST ANSWER

Here is how for loop of the form

for (ForInit; ForCondition; ForUpdate)
  Body

is executed:

  1. ForInit is executed
  2. ForCondition is evaluated
    • when false, then Body is not executed and execution continues after loop
    • when true, then Body is executed, ForUpdate is executed and execution continues from step 2

"2 branches" correspond to the above two options for ForCondition.

"1 of 2 branches missing" means that happened only one of these options, either first one, or second one.


In absence of complete example that includes body of your loop, hard to answer your additional questions

But strange -- why then other loops that always executed at least once are green?

Yet it's rather strange -- why other loops are always green?

However given that Body of your loop was executed, possible that there is exit from the loop in the Body before ForCondition evaluates to false.

For example using latest as of today version 2018-12 of Eclipse IDE for Java that comes with EclEmma 3.1.1:

example

And maybe there is no such exits in your other loops:

example

This can also explain

Running this code with an empty StringBuilder paints it green.

and

Adding an artificially created situation with an empty StringBuilder (that's impossible in reality) colors the loop in green.

because of added case when ForCondition evaluates to false before execution of Body:

example

4
Mureinik On

I'm guessing the missing branches refer to the condition i >= 0. Since i is initialized with a positive maxIdx (according to the comments), you should probably also add test cases for maxIdx of 0 and a negative maxIdx.

Note that since maxIdx is the length of a StringBuilder (according to the comments), this may not be possible, and you'd have to either live with the missing branch, or "artificially" refactor your code so that you can pass a negative maxIdx.