Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 202
Christian Avatar asked Jul 21 '15 17:07

Christian


People also ask

What is JaCoCo branch coverage?

Branches (C1 Coverage) JaCoCo also calculates branch coverage for all if and switch statements. This metric counts the total number of such branches in a method and determines the number of executed or missed branches. Branch coverage is always available, even in absence of debug information in the class files.

How do you cover code coverage?

To calculate the code coverage percentage, simply use the following formula: Code Coverage Percentage = (Number of lines of code executed by a testing algorithm/Total number of lines of code in a system component) * 100.

How do I increase my JaCoCo branch coverage?

To efficiently cover all 6 branches in this case, the test function must be called no less than 4 times to achieve 100% branch coverage. Save this answer. Show activity on this post.

What is statement coverage in unit testing?

What is Statement Coverage? It is one type of white box testing technique that ensures that all the statements of the source code are executed at least once. It covers all the paths, lines, and statements of a source code.


1 Answers

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.

like image 186
Tagir Valeev Avatar answered Sep 19 '22 02:09

Tagir Valeev