Eclemma:在 for-loop 中遗漏了分支——这是什么意思?

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

测试我的代码我遇到了一个我无法解释的事情。使用 eclemma 检查代码覆盖率,我发现 for-loop 的 header 以黄色突出显示,消息为 "1 of 2 branches missing".

代码行如下:

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

循环的body被高亮显示为覆盖(并实际执行),以及前后语句,并且该方法在所有可能的条件下都可以正常工作。据我所知,其他 for-loops 的 header 仅在循环的 body 从未执行过的情况下以黄色突出显示并显示相同的消息。

这条消息的意义是什么?缺少哪个分支?

我猜缺少的分支指的是条件 i >= 0。由于 i 是用正 maxIdx 初始化的(根据评论),您可能还应该为 0maxIdx 和负 maxIdx 添加测试用例.

请注意,由于 maxIdxStringBuilder 的长度(根据评论),这可能是不可能的,您将不得不接受缺少的分支,或者"artificially" 重构您的代码,以便您可以传递负值 maxIdx

下面是 for 形式循环的方式

for (ForInit; ForCondition; ForUpdate)
  Body

被执行:

  1. ForInit执行
  2. ForCondition被评价
    • false时,则Body不执行,循环
    • 后继续执行
    • true时,则执行Body,执行ForUpdate,从第2步继续执行

“2支”对应以上两个选项ForCondition.

“缺少 2 个分支中的 1 个”意味着只发生了这些选项中的一个,第一个或第二个。


由于缺少包含循环主体的 complete example,很难回答您的其他问题

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?

然而,鉴于执行了循环的 Body,可能在 ForCondition 计算为 false 之前的 Body 中退出循环。

例如,使用 EclEmma 3.1.1 随附的 Java 的 Eclipse IDE 的最新版本 2018-12:

也许你的其他循环中没有这样的出口:

这也可以解释

Running this code with an empty StringBuilder paints it green.

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

因为在执行 Body 之前 ForCondition 计算结果为 false 时增加了大小写: