I faced a frustrating problem with jacoco and ternary operations in Java. Context:
I have a function which take a List<String>
. The max filters this list can have is 10 and they can be set or not. I choosed to do ternary to fill the filters string.
In my JUnit test, I call twice this function: once with 10 filters and once with none. However, jacoco is still telling me that 1 of 2 branches is missed.
I voluntarily changed the names / returns of my functions to show only the global scheme
public void functionToTest(List<String> filters){
String p0 = filters.get(0);
String p1 = filters.size() >= 2 ? filters.get(1) : "";
String p2 = filters.size() >= 3 ? filters.get(2) : "";
String p3 = filters.size() >= 4 ? filters.get(3) : "";
String p4 = filters.size() >= 5 ? filters.get(4) : "";
String p5 = filters.size() >= 6 ? filters.get(5) : "";
String p6 = filters.size() >= 7 ? filters.get(6) : "";
String p7 = filters.size() >= 8 ? filters.get(7) : "";
String p8 = filters.size() >= 9 ? filters.get(8) : "";
String p9 = filters.size() >= 10 ? filters.get(9) : "";
// Do stuff with filters
}
@Test
public void testFunction() {
List<String> filters = //instantiate 10 strings
// First call with no filters
functionToTest(Collections.emptyList());
// Second call with filters
functionToTest(filters);
}
Here is the result of jacoco saying "1 of 2 branches missed" on yellow lines:
So my question is: Is there a way to "bypass" or to deal with ternary operations and jacoco ?
NB: I already know how to solve the coverage but it is ugly, see:
String p1 = ""
if (filters.size() >=2) {
p1 = filters.get(1);
}
// etc...
Solved, I was just dumb
I forgot that I tested if the list was empty before, if it is, I return something else.