Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exclude a line from jacoco code coverage?

How would i exclude inputStream.close() from jacoco code coverage, in pom.xml or in the java code?

public void run() {
    InputStream inputStream = null;
    try {
        inputStream = fileSystem.newFileInputStream(file);
    }
    finally {
        if(inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {}
        }
    }
}
like image 519
nommer Avatar asked Oct 24 '17 17:10

nommer


People also ask

How do I exclude a method in JaCoCo?

Starting from JaCoCo 0.8. 2, we can exclude classes and methods by annotating them with a custom annotation with the following properties: The name of the annotation should include Generated. The retention policy of annotation should be runtime or class.

How do you exclude test coverage?

Excluding code from code coverage The easiest way to exclude code from code coverage analysis is to use ExcludeFromCodeCoverage attribute. This attribute tells tooling that class or some of its members are not planned to be covered with tests.

What is line coverage JaCoCo?

JaCoCo mainly provides three important metrics: Lines coverage reflects the amount of code that has been exercised based on the number of Java byte code instructions called by the tests. Branches coverage shows the percent of exercised branches in the code, typically related to if/else and switch statements.


2 Answers

I suspect what you're really aiming for is 100% coverage. Consider re-writing the code using a try-with-resources block instead. For example:

try (final InputStream inputStream = new FileInputStream(file)){
    //work with inputStream; auto-closes
}
catch (final Exception ex){
    //handle it appropriately
}
like image 121
Domenic D. Avatar answered Sep 22 '22 22:09

Domenic D.


As for now, there's no ability to exclude a specific line (see the link):

As of today JaCoCo core only works on class files, there is no source processing. This would require a major rework of the architecture and adds additional configuration hassles.

It means, Jacoco analyzes byte code of your program, not your sources, as the result it cannot use hints like comments.

Follow the corresponding issue to track the status of such feature implementation.

As a workaround you can put it into a separate method, but see, it's a bad smell when you change your code just to reach 100% coverage level.

like image 44
GoodDok Avatar answered Sep 22 '22 22:09

GoodDok