Test coverage for if statement with logical or (||) - with Java's short circuiting, what's the forth condition JaCoCo wants me to cover?

坚强是说给别人听的谎言 提交于 2019-12-13 13:12:41

问题


This is probably a rather simple question, but I'm at a loss...

I have an if statement like the following:

if(TheEnum.A.equals(myEnum) || TheEnum.B.equals(myEnum))

TheEnum can be A, B, C, ... G (more than just 4 options).

JaCoCo (SONAR) tells me that there are four conditions I can cover here. Which ones are those? Isn't the entire set I can test for in this instance essentially

if(true || not_evaluated) => true
if(false || true) => true
if(false || false) => false

I'm pretty sure I can't specifically test for if(true || true) or if(true || false), as short circuit evaluation won't get that far...?

If so, what is the forth option JaCoCo/Sonar wants me to test for?


回答1:


You are right, this code is short-circuiting. It's compiled into bytecode roughly like this (assuming Java has goto):

if(TheEnum.A.equals(myEnum)) goto ok;
if(!TheEnum.B.equals(myEnum)) goto end;
ok:
   // body of if statement
end:

So as JaCoCo analyzes the bytecode, from its point of view you have the two independent checks: first if and second if, which generate four possible branches. You may consider this as a JaCoCo bug, but I guess it's not very easy to fix this robustly and it is not very disturbing, so you can live with it.



来源:https://stackoverflow.com/questions/31546047/test-coverage-for-if-statement-with-logical-or-with-javas-short-circuiti

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!