1

When I run coverage on my code below:

  private static String mapMyVal(String val) {
    switch (val) {
      case "foo":
        return "FOO_FOO";
      case "bar":
        return "BARR";
      default:
        throw new InvalidArgumentException();
    }
  }

I see "8 out of 10 conditions covered" when I run my unit tests on this with coverage. However I see all three lines being covered inside the statement.

Since there are no other conditions than "foo", "bar" and everything else, what are those missing two conditions?

Layman
  • 797
  • 1
  • 7
  • 23

2 Answers2

3

I see one possible case not covered. The input val might be null. In that case, your switch statement would throw a NullPointerException. To remedy this, you could add null check to the start of the method.

private static String mapMyVal(String val) {
    switch (val) {
        case "foo":
            return "FOO_FOO";
        case "bar":
            return "BARR";
        default:
            throw new InvalidArgumentException();
    }
}
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • 1
    @Nexevis You're right, and I retract what I wrote initially. But the `null` input edge case should be a concern. – Tim Biegeleisen Jan 30 '20 at 16:50
  • Good point. In my use case I am handling it before calling this method though e.g. null values never reach the method. Should coverage still consider `null` as a possible value? – Layman Jan 30 '20 at 16:52
1

There was already someone asking nearly the same question. Overall it turned out that going for 100% of unittest for a switch-case might be pure luck because of the way that java is handling the switch-case. See here eclemma branch coverage for switch: 7 of 19 missed

funky
  • 313
  • 3
  • 8
  • 14
  • But those answers are from 2015. Surely issues with bytecode inspection that are described there were addressed over the last four years? – M. Prokhorov Jan 30 '20 at 17:02
  • Actually there is an blogentry in the web from the 14 Jan 2019 in which my linked answer is used as a resource. The author gets the same problem/result as the one I mentioned. – funky Jan 30 '20 at 17:12