100% condition coverage impossible to get with enums

As stated in java - Miscounting switch conditions with enum in SonarQube - Stack Overflow it’s impossible to get 100% code coverage with enums due to SonarQube complaining that a condition is not tested that can’t be tested.

Supposing I have an enum

enum Test {
  A1,
  A2
}

And this code:

if (A1.equals(var)) {
  // Some code
} else if (A2.equals(var)) {
  // Some other
}

or

switch (var) {
  case A1:
    // Some code
    break;
  case A2:
    // Some other code
    break;
  default:
    // Some error
    break;
}

SonarQube will complain that there is a branch not tested. In this case, even if tests are covering A1 and A2, it will complaint that there’s still a test missing for something that isn’t A1 or A2 but there isn’t any way to test this third option because, being an enum, I can’t test with something that it’s not already a valid enum value. The only options I see are:

  • Create a third value only to satisfy Sonar but that will impact the code as, for someone who’s using your enum, it’s not clear that any value is only there to get some coverage goals.
  • Only test for A1 and leave the code path for A2 in a simple else or in the default branch. But that’s dangerous if, for whatever reason, at some point there is an A3 value since it will be treated as A2 in several parts of the code while checking explicitly for A2 will not have this side effect.

Sonar should check this case when using enums. If all paths of a condition tree are covered by values of the enum already tested, it should treat it as 100% coverage.

Hi,

To be clear, it’s not SonarQube complaining. SonarQube doesn’t assess what is and is not covered. It merely reflects to you what your coverage engine (JaCoCo?) says is or is not covered. To sort this out, you’ll need to go back to the maintainers of the project that generates your coverage reports.

 
:woman_shrugging:
Ann