简体   繁体   English

使用 Gradle 过滤 JaCoCo 覆盖率报告

[英]Filter JaCoCo coverage reports with Gradle

Problem:问题:

I have a project with and I want to be able to filter certain classes and/or packages.我有一个项目,我希望能够过滤某些类和/或包。

Related Documentation:相关文档:

I have read the following documentation:我已阅读以下文档:

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

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

Official Github issues, working on coverage: https://github.com/jacoco/jacoco/wiki/FilteringOptions https://github.com/jacoco/jacoco/issues/14官方 Github问题,覆盖范围: 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 ) 使用 Sonarrunner 和 Gradle 从 Jacoco 报告中排除软件包(不使用

JaCoCo - exclude JSP from report (It seems to work for , I am using ) JaCoCo - 从报告中排除 JSP (它似乎适用于 ,我正在使用

Maven Jacoco Configuration - Exclude classes/packages from report not working (It seems to work for , I am using ) Maven Jacoco 配置 - 从报告中排除类/包不起作用(它似乎适用于 ,我正在使用

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 coverage reports?生成覆盖率报告时如何排除某些包和类?

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 forums!在 Google 搜索、阅读 Gradle 文档并浏览较旧的 StackOverflow 帖子后,我在官方论坛上找到了这个答案!

jacocoTestReport {
    afterEvaluate {
        classDirectories.setFrom(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

For older gradle versions < 5.x may need to use classDirectories = files(classDirectories.files.collect { instead of classDirectories.setFrom对于较旧的 gradle 版本 < 5.x 可能需要使用classDirectories = files(classDirectories.files.collect {而不是classDirectories.setFrom

Solution to my build.gradle for Java/Groovy projects:我的build.gradle for 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

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/**')
        }))
    }
}

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#N16E62 and 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

For Gradle6 Use something like below, because they made classDirectories as final , we cannot re-assign it, but a setter method exists classDirectories.setFrom which can be utilized对于 Gradle6 使用类似下面的东西,因为他们把classDirectories as final ,我们不能重新分配它,但是一个 setter 方法存在classDirectories.setFrom可以使用

    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/**'
                    ]
            )
        }))
    }
}

In order to filter in jacoco report, exclusion need to be done in two task jacocoTestReport and jacocoTestCoverageVerification .为了在 jacoco 报告中进行过滤,需要在两个任务jacocoTestReportjacocoTestCoverageVerification

sample code示例代码

    def jacocoExclude = ['**/example/**', '**/*Module*.class']

    jacocoTestReport {
        afterEvaluate {
            getClassDirectories().setFrom(classDirectories.files.collect {
                fileTree(dir: it, exclude: jacocoExclude)
            })
        }
    }

    jacocoTestCoverageVerification {
        afterEvaluate {
            getClassDirectories().setFrom(classDirectories.files.collect {
                fileTree(dir: it, exclude: jacocoExclude)
            })
        }

        ...
    }



Here is a solution for this problem in ANT. 是 ANT 中针对此问题的解决方案。 This can be adapted to gradle by adding the following under the jacocoTestReport task.这可以通过在jacocoTestReport任务下添加以下内容来适应jacocoTestReport Although this isn't really documented by jacoco, it seems like the only way to filter the test results for now.尽管 jacoco 并没有真正记录这一点,但它似乎是目前过滤测试结果的唯一方法。

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

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/ main in your classDirectories config 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
                     ]
        )
    }
}

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/**'])
        })
    }
}

For those who still scratching their heads to filter certain packages from the coverage report, here is the configuration that works for me using the most recent libraries.对于那些仍然在摸索从覆盖率报告中过滤某些包的人来说,这里是使用最新库的对我有用的配置。

   Build tool: Gradle 6.5 (also tried for 6.7)
   Coverage Tool: Jacoco 0.8.5

Things to consider/Justifications需要考虑的事项/理由

  • afterScript is not required afterScript
  • Need to exclude it twice, one for report generation and coverage verification需要排除两次,一次用于报告生成和覆盖率验证
  • The intellij IDE recommends to use excludes param instead of exclude . Intellij IDE 建议使用excludes参数而不是exclude Either of which just works fine任何一个都可以正常工作
  • While providing the regex, be sure to provide the .class files and not the .java files.在提供正则表达式时,请务必提供.class文件而不是.java文件。
  • Post Gradle 5, classDirectories is a read-only field, therefore, use classDirectories.setFrom Post Gradle 5, classDirectories是只读字段,因此,使用classDirectories.setFrom
jacocoTestReport {
    doLast {
        println("See report file://${project.rootDir}/build/reports/jacoco/test/html/index.html")
    }
    excludedClassFilesForReport(classDirectories)
}

jacocoTestCoverageVerification {
    excludedClassFilesForReport(classDirectories)
    violationRules {
        rule {
            limit {
                minimum = 0.55
            }
        }
    }
}

private excludedClassFilesForReport(classDirectories) {
    classDirectories.setFrom(files(classDirectories.files.collect {
        fileTree(dir: it, exclude: [
                '**/common/apigateway/*.class',a
                '**/common/*/client/*Client*.class',
                '**/configuration/*ClientConfiguration.class',
                '**/model/search/*SearchService.class'
        ])
    }))
}

check.dependsOn jacocoTestCoverageVerification

For me, i have to do exclude in 2 places对我来说,我必须在 2 个地方排除

jacocoTestReport {
    dependsOn test // tests are required to run before generating the report


    afterEvaluate {
        excludedClassFilesForReport(classDirectories)
    }
}

jacocoTestCoverageVerification {

    afterEvaluate {
        excludedClassFilesForReport(classDirectories)
    }
}

private excludedClassFilesForReport(classDirectories) {
    classDirectories.setFrom(files(classDirectories.files.collect {
        fileTree(dir: it,
            exclude: [
                    'com/test/a/config/**',
                    'com/test/b/constant/**',
                    'com/test/c/MainApp.class'
            ]
    )
}))
}

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/**')
    }))
}

For anyone going out of their mind looking for this answer in Kotlin DSL, here it is:对于任何想在 Kotlin DSL 中寻找这个答案的人来说,这里是:

val jacocoExclude = listOf("**/entities/**", "**/dtos/**")
jacocoTestReport {
    reports {
        xml.isEnabled = true
        csv.isEnabled = false
    }
    classDirectories.setFrom(classDirectories.files.map {
        fileTree(it).matching {
            exclude(jacocoExclude)
        }
        })
}
test {
    useJUnitPlatform()
    systemProperty("gradle.build.dir", project.buildDir)
    finalizedBy(jacocoTestReport)
    extensions.configure(JacocoTaskExtension::class) {
        excludes = jacocoExclude
    }
}

for Kotlin users, here is what I used (gradle 6.7)对于 Kotlin 用户,这是我使用的(gradle 6.7)

build.gradle.kts build.gradle.kts

tasks.jacocoTestReport {
    // tests are required to run before generating the report
    dependsOn(tasks.test) 
    // print the report url for easier access
    doLast {
        println("file://${project.rootDir}/build/reports/jacoco/test/html/index.html")
    }
    classDirectories.setFrom(
        files(classDirectories.files.map {
            fileTree(it) {
                exclude("**/generated/**", "**/other-excluded/**")
            }
        })
    )
}

as suggested here : https://github.com/gradle/kotlin-dsl-samples/issues/1176#issuecomment-610643709如此处建议: https : //github.com/gradle/kotlin-dsl-samples/issues/1176#issuecomment-610643709

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

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

Gradle 6.8.3 thrown an exception. Gradle 6.8.3 抛出异常。 Cannot set the value of read-only property 'classDirectories' for task ':jacocoTestReport' of type org.gradle.testing.jacoco.tasks.JacocoReport.

so I found a way to fix the issue by using所以我找到了一种方法来解决这个问题

classDirectories.setFrom(
            fileTree(dir: "build/classes/java/main")
                    .filter({file -> !file.path.contains('/dir1')})
                    .filter({file -> !file.path.contains('/dir2')})
                    .filter({file -> !file.path.contains('/dir3')})
    )

Here is my working config in Gradle with Jacoco 0.8.5 :这是我在 Gradle 中使用 Jacoco 0.8.5 的工作配置:

def jacocoExclusions = [
        '**/config/*Config.class',
        '**/config/*Advice.class',
        '**/security/*AuthorityRoles.class',
        '**/*Application.class'
];

jacocoTestReport {
  reports {
    xml.enabled false
    csv.enabled false
    html.destination file("${buildDir}/reports/jacocoHtml")
  }
  afterEvaluate {
    classDirectories.setFrom(files(classDirectories.files.collect {
      fileTree(dir: it,
              exclude: jacocoExclusions
      )
    }))
  }
}

jacocoTestCoverageVerification {
  afterEvaluate {
    classDirectories.setFrom(files(classDirectories.files.collect {
      fileTree(dir: it,
              exclude: jacocoExclusions
      )
    }))
  }
  violationRules {
    rule {
      excludes = jacocoExclusions
      limit {
        minimum = 0.90
      }
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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