0

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:

jacoco result

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...
Pommepomme
  • 115
  • 1
  • 11
  • Are you sure that you accurately describe the actual code? I ask because when you call `functionToTest(Collections.emptyList())` the line `String p0 = filters.get(0)` should throw an `IndexOutOfBoundsException`. – Thomas Kläger Dec 09 '22 at 17:26
  • Aaaaaah indeed, I have something else before ```JAVA if (filters.isEmpty()) { // return do stuff } p0 = filters.get(0) [......] ``` – Pommepomme Dec 09 '22 at 17:32
  • That explains the outcome. For full coverage of the ternaries you need to supply once one argument and once 10 arguments. – Thomas Kläger Dec 09 '22 at 17:37
  • Yep, I just focused on the yellow parts forgetting the `if empty` before.... My bad! – Pommepomme Dec 09 '22 at 17:41

1 Answers1

0

Solved, I was just dumb

I forgot that I tested if the list was empty before, if it is, I return something else.

Pommepomme
  • 115
  • 1
  • 11