4

Using the latest version (4.3.2) of SonarQube, a try-with-resources block gives a false positive to branch coverage of the catch line. For example:

public List<String> getLines(String filename) {
    try (InputStream inputStream = getInputStream(filename)){
        return IOUtils.readLines(inputStream);
    } catch (IOException e) { // <<<<<<< REPORTS AS BRANCH COVERAGE 2/8 
        throw new IllegalArgumentException(e);
    }
}

But my unit tests cover exceptions thrown at every point, and all other lines have 100% coverage - the actual coverage is 100%. And where's the "8" coming from? There's aren't 8 places that an exception can the thrown.

I tried adding // NOSONAR to the problem line, and even tried adding it to every line, but the report is the same.

Other types of problem were ignored when using // NOSONAR, so it's not a sonar configuration problem.

I suspect it's because sonar doesn't allow for the extra try-catch blocks in the bytecode that a try-with-resources block produces.

Is there a way to decorate the code that successfully causes sonar to ignore this particular false positive?

Bohemian
  • 412,405
  • 93
  • 575
  • 722

1 Answers1

8

SonarQube does not support Java try-with-resources constructs.

It also reports a bogus null-check issue on use.

Since SonarQube is using other tools (PMD/FindBugs, etc) and they use byte-code analysis, they (admittedly) say that sometimes these are false-positives. The answer the "SonarQube Way" is to NOT use try-with-resources until they have proper handling of the resulting byte-code.

However, no sane developer would recommend having the tail wag the dog. My suggestion is to mark as false-positve via SonarQube plug-ins but it will not help about test-coverage because its analysis of the byte-code in this case is just wrong.

SonarQube itself has thousands of issues (they eat their own dog food).

dcsohl
  • 7,186
  • 1
  • 26
  • 44
Darrell Teague
  • 4,132
  • 1
  • 26
  • 38
  • There is apparently a fix for this in SonarCube updates, at least to stop reporting the "null check" false-positive. It does not speak to whether it fixes the resulting test-coverage due to the way the byte-code gets put together to handle exceptions but these links may be useful: http://stackoverflow.com/questions/17354150/8-branches-for-try-with-resources-jacoco-coverage-possible and http://www.sonarqube.org/sonar-2-12-in-screenshots/ – Darrell Teague Jul 31 '14 at 14:43