Search code examples
javafor-loopcode-coverageeclemma

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


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?


Solution

  • 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