如何从 jacoco 代码覆盖范围中排除一行?

How to exclude a line from jacoco code coverage?

如何在 pom.xml 或 java 代码中从 jacoco 代码覆盖范围中排除 inputStream.close()

public void run() {
    InputStream inputStream = null;
    try {
        inputStream = fileSystem.newFileInputStream(file);
    }
    finally {
        if(inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {}
        }
    }
}

我认为没有办法排除特定的陈述。但是,有一项排除方法 though its not recommended 的规定。作为一种糟糕的解决方法,我们可以在语句之外创建方法。 JaCoCo 的 0.8.2 版本中添加了新功能,过滤掉带有 @Generated 注释的方法。有关详细信息,请参阅以下文档:

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

参考https://github.com/jacoco/jacoco/wiki/FilteringOptions#annotation-based-filtering了解更多信息。

我怀疑您的真正目标是 100% 的覆盖率。考虑改用 try-with-resources 块重写代码。例如:

try (final InputStream inputStream = new FileInputStream(file)){
    //work with inputStream; auto-closes
}
catch (final Exception ex){
    //handle it appropriately
}

嗯,你不能。如果您想从覆盖范围中排除某些使 class 覆盖范围低于某些强制限制的行,则只需排除整个 class 或包。您可以在此处找到更多信息:

至于现在,无法排除特定行(参见 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.

这意味着,Jacoco 分析的是您程序的字节码,而不是您的源代码,因此它 cannot use hints like comments

关注 the corresponding issue 以跟踪此类功能实施的状态。

作为解决方法,您可以将它放入一个单独的方法中,但是您看,当您更改代码只是为了达到 100% 的覆盖率水平时,它会发出难闻的气味。