Question

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?

Was it helpful?

Solution

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top