简体   繁体   中英

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) {}
        }
    }
}

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
}

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.

I don't think there is a way to exclude a particular statement. However, there is a provision to exclude a method, though its not recommended .As a bad workaround we can create method out of statement. The new feature has been added in the 0.8.2 release of JaCoCo which filters out the methods annotated with @Generated . For details please see the documentation below:

Classes and methods annotated with runtime visible and invisible annotation whose simple name is Generated are filtered out during generation of report

Refer https://github.com/jacoco/jacoco/wiki/FilteringOptions#annotation-based-filtering for more information.

Well you can't. If you want to exclude from coverage some line which drops down the class coverage below some mandatory limit, then just exclude whole class or package. You can find more information here: Maven Jacoco Configuration - Exclude classes/packages from report not working

Possibly make a line to ignore a separate method. You can exclude a method by annotating it.

I used this post: How would I add an annotation to exclude a method from a jacoco code coverage report?

because I wanted to exclude the initBinder() Spring callback in a RestController.

So I have this:

  @ExcludeFromJacocoGeneratedReport
  @InitBinder
  private void initBinder(WebDataBinder binder) {
      binder.setValidator(myInjectedDtoValidator);
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM