Java 使用 Gradle 过滤 JaCoCo 覆盖率报告

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29887805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 08:47:02  来源:igfitidea点击:

Filter JaCoCo coverage reports with Gradle

javaunit-testinggradlecode-coveragejacoco

提问by Jared Burrows

Problem:

问题:

I have a project with jacocoand I want to be able to filter certain classes and/or packages.

我有一个jacoco项目,我希望能够过滤某些类和/或包。

Related Documentation:

相关文档:

I have read the following documentation:

我已阅读以下文档:

Official jacocosite:http://www.eclemma.org/jacoco/index.html

jacoco官方网站:http : //www.eclemma.org/jacoco/index.html

Official jacocodocs for gradle:https://gradle.org/docs/current/userguide/jacoco_plugin.html

gradle 的官方jacoco文档:https : //gradle.org/docs/current/userguide/jacoco_plugin.html

Official jacocoGithubissues, working on coverage:https://github.com/jacoco/jacoco/wiki/FilteringOptionshttps://github.com/jacoco/jacoco/issues/14

官方jacocoGithub问题,正在处理:https : //github.com/jacoco/jacoco/wiki/FilteringOptions https://github.com/jacoco/jacoco/issues/14

Related StackOverflow Links:

相关 StackOverflow 链接:

JaCoCo & Gradle - Filtering Options(No answer)

JaCoCo & Gradle - 过滤选项(无答案)

Exclude packages from Jacoco report using Sonarrunner and Gradle(Not using sonar)

使用 Sonarrunner 和 Gradle 从 Jacoco 报告中排除包(不使用sonar

JaCoCo - exclude JSP from report(It seems to work for maven, I am using gradle)

JaCoCo - 从报告中排除 JSP(它似乎适用于maven,我正在使用gradle

Maven Jacoco Configuration - Exclude classes/packages from report not working(It seems to work for maven, I am using gradle)

Maven Jacoco 配置 - 从报告中排除类/包不起作用(它似乎适用于Maven,我正在使用gradle

JaCoCo gradle plugin exclude(Could not get this to work)

JaCoCo gradle 插件排除(无法让它工作)

Gradle Jacoco - coverage reports includes classes excluded in configuration(Seems very close, it used doFirst, did not work for me)

Gradle Jacoco - 覆盖率报告包括配置中排除的类(似乎非常接近,它使用过doFirst,对我不起作用)

Example of what I have tried:

我尝试过的示例:

apply plugin: 'java'
apply plugin: 'jacoco'

buildscript {
    repositories {
        mavenCentral()
        jcenter()
    }
}

repositories {
    jcenter()
}

jacocoTestReport {
    reports {
        xml {
            enabled true // coveralls plugin depends on xml format report
        }

        html {
            enabled true
        }
    }

    test {
        jacoco {
            destinationFile = file("$buildDir/jacoco/jacocoTest.exec")
            classDumpFile = file("$buildDir/jacoco/classpathdumps")
            excludes = ["projecteuler/**"] // <-- does not work
            // excludes = ["projecteuler"]
        }
    }
}

Question:

题:

How can I exclude certain packages and classes when generating the jacococoverage reports?

生成jacoco覆盖率报告时如何排除某些包和类?

采纳答案by Jared Burrows

Thanks to, Yannick Welsch:

感谢,Yannick Welsch

After searching Google, reading the Gradle docs and going through older StackOverflow posts, I found this answer on the Official gradleforums!

在 Google 搜索、阅读 Gradle 文档并浏览较旧的 StackOverflow 帖子后,我在官方gradle论坛上找到了这个答案!

jacocoTestReport {
    afterEvaluate {
        classDirectories = files(classDirectories.files.collect {
            fileTree(dir: it, exclude: 'com/blah/**')
        })
    }
}

Source:https://issues.gradle.org/browse/GRADLE-2955

来源:https : //issues.gradle.org/browse/GRADLE-2955

Solution to my build.gradlefor Java/Groovy projects:

build.gradle的 Java/Groovy 项目的解决方案:

apply plugin: 'java'
apply plugin: 'jacoco'

jacocoTestReport {
    reports {
        xml {
            enabled true // coveralls plugin depends on xml format report
        }

        html {
            enabled true
        }
    }

    afterEvaluate {
        classDirectories = files(classDirectories.files.collect {
            fileTree(dir: it,
                    exclude: ['codeeval/**',
                              'crackingthecode/part3knowledgebased/**',
                              '**/Chapter7ObjectOrientedDesign**',
                              '**/Chapter11Testing**',
                              '**/Chapter12SystemDesignAndMemoryLimits**',
                              'projecteuler/**'])
        })
    }
}

As you can see, I was successfully able to add more to exclude:in order to filter a few packages.

如您所见,我成功地添加了更多内容exclude:以过滤一些包。

Source:https://github.com/jaredsburrows/CS-Interview-Questions/blob/master/build.gradle

来源:https : //github.com/jaredsburrows/CS-Interview-Questions/blob/master/build.gradle

Custom tasks for other projects such as Android:

Android 等其他项目的自定义任务:

apply plugin: 'jacoco'

task jacocoReport(type: JacocoReport) {
    reports {
        xml {
            enabled true // coveralls plugin depends on xml format report
        }

        html {
            enabled true
        }
    }

    afterEvaluate {
        classDirectories = files(classDirectories.files.collect {
            fileTree(dir: it,
                    exclude: ['codeeval/**',
                              'crackingthecode/part3knowledgebased/**',
                              '**/Chapter7ObjectOrientedDesign**',
                              '**/Chapter11Testing**',
                              '**/Chapter12SystemDesignAndMemoryLimits**',
                              'projecteuler/**'])
        })
    }
}

Source:https://github.com/jaredsburrows/android-gradle-java-app-template/blob/master/gradle/quality.gradle#L59

来源:https : //github.com/jaredsburrows/android-gradle-java-app-template/blob/master/gradle/quality.gradle#L59

回答by Andre Compagno

Hereis a solution for this problem in ANT. This can be adapted to gradle by adding the following under the jacocoTestReporttask. Although this isn't really documented by jacoco, it seems like the only way to filter the test results for now.

是 ANT 中针对此问题的解决方案。这可以通过在jacocoTestReport任务下添加以下内容来适应 gradle 。尽管 jacoco 并没有真正记录这一点,但它似乎是目前过滤测试结果的唯一方法。

afterEvaluate {
    classDirectories = files(classDirectories.files.collect {
        fileTree(dir: it, exclude: 'excluded/files/**')
    })
}

回答by Randy

This has been out for a while, but I just ran across this. I was struggling with all the exclusions needed. I found it was something much more simple for me. If you follow the Maven project layout style /src/main/java and /src/test/java, you simply need to put buildDir/classes/mainin your classDirectoriesconfig like so:

这已经有一段时间了,但我刚刚遇到了这个。我正在为所有需要的排除而苦苦挣扎。我发现这对我来说要简单得多。如果您遵循 Maven 项目布局样式 /src/main/java 和 /src/test/java,您只需要将buildDir/classes/ main放在您的classDirectories配置中,如下所示:

afterEvaluate {
    jacocoTestReport {
        def coverageSourceDirs = ['src/main/java']
        reports {
            xml.enabled false
            csv.enabled false
            html.destination "${buildDir}/reports/jacocoHtml"
        }
        sourceDirectories = files(coverageSourceDirs)
        classDirectories = fileTree(
                dir: "${project.buildDir}/classes/main",
                excludes: [
                      //whatever here like JavaConfig etc. in /src/main/java
                     ]
        )
    }
}

回答by childno?.de

for me, it's fine working with

对我来说,和我一起工作很好

test {
  jacoco {
    excludes += ['codeeval/**',
                 'crackingthecode/part3knowledgebased/**',
                 '**/Chapter7ObjectOrientedDesign**',
                 '**/Chapter11Testing**',
                 '**/Chapter12SystemDesignAndMemoryLimits**',
                 'projecteuler/**']
  }
}

as stated out in documentation https://docs.gradle.org/current/userguide/jacoco_plugin.html#N16E62and initally asked so the answer is:

如文档 https://docs.gradle.org/current/userguide/jacoco_plugin.html#N16E62 中所述,最初被问到,所以答案是:

so if you ask me: it's not a question of

所以如果你问我:这不是一个问题

excludes = ["projecteuler/**"]

or

或者

excludes += ["projecteuler/**"]

but

excludes = ["**/projecteuler/**"]

to exclude a package *.projecteuler.*

排除一个包 *.projecteuler.*

and test {}on project level, not nested in jacocoTestReport

test {}在项目级别,不嵌套jacocoTestReport

回答by er-han

The code below excludes classes from coverage verification as well:

下面的代码也从覆盖率验证中排除了类:

jacocoTestCoverageVerification {
    afterEvaluate {
        classDirectories = files(classDirectories.files.collect {
            fileTree(dir: "${project.buildDir}/classes/main",
                    exclude: ['**/packagename/**'])
        })
    }
}

回答by uwe

For Gradle version 5.x, the classDirectories = files(...)gives a deprecation warning and does not work at all starting from Gradle 6.0 This is the nondeprecated way of excluding classes:

对于 Gradle 5.x 版,classDirectories = files(...)给出了弃用警告并且从 Gradle 6.0 开始根本不起作用这是排除类的非弃用方法:

jacocoTestReport {
    afterEvaluate {
        classDirectories.setFrom(files(classDirectories.files.collect {
            fileTree(dir: it, exclude: 'com/exclude/**')
        }))
    }
}

回答by Bharat

add below config in gradle.properties file

在 gradle.properties 文件中添加以下配置

coverageExcludeClasses=["com.example.package.elasticsearch.*", "com.example.package2.*",]

coverageExcludeClasses=["com.example.package.elasticsearch.*", "com.example.package2.*",]

回答by riiich

some comments mentioned the deprecation warning. to solve just use the getter:

一些评论提到了弃用警告。解决只需使用吸气剂:

afterEvaluate {
    getClassDirectories().from(files(classDirectories.files.collect {
        fileTree(dir: it, exclude: 'com/blah/**')
    }))
}

回答by Ankur Srivastava

For Gradle6 Use something like below, because they made classDirectories as final, we cannot re-assign it, but a setter method exists classDirectories.setFromwhich can be utilized

对于 Gradle6 使用类似下面的东西,因为他们做了classDirectories as final,我们不能重新分配它,但是存在classDirectories.setFrom一个可以使用的 setter 方法

    jacocoTestReport {
    reports {
        xml.enabled true
        html.enabled true
        html.destination file("$buildDir/reports/jacoco")
    }

    afterEvaluate {
        classDirectories.setFrom(files(classDirectories.files.collect {
            fileTree(dir: it,
                    exclude: ['**/server/**',
                              '**/model/**',
                              '**/command/**'
                    ]
            )
        }))
    }
}