JaCoCo Gradle - 排除 类 并覆盖包含

JaCoCo Gradle - Exclude classes & override Includes

我正在尝试改进我的项目中的代码覆盖率,并希望排除任何 View 类(因为它们不是 tested/testable)但包括任何 ViewModel 类...但我似乎无法让通配符过滤器配合,要么全有要么全无!


def excludedPatterns = [
        //... other stuff

        '**/*Fragment*.*',
        '**/*Activity*.*',
        '**/*Adapter*.*',

        '**/*View*.*', // <-- this line is excluding classes ending w/ ViewModel

        '**/*ViewState*.*',
        '**/*ViewHolder*.*',
]

task codeCoverageReport(type: JacocoReport, dependsOn: 'testDebugUnitTest') {
    group = "Reporting"
    description = "Generate Jacoco coverage reports after running tests."

    reports {
        html.enabled true
    }

    def debugTree = fileTree(
            dir: "$project.buildDir/tmp/kotlin-classes/debug",
            excludes: excludedPatterns
    )
    classDirectories.from = files([debugTree])

    def mainSrc = "$project.projectDir/src/main/java"
    sourceDirectories.from = files([mainSrc])

    executionData.from = fileTree(dir: project.buildDir, includes: [
            'jacoco/testDebugUnitTest.exec',
            'outputs/code-coverage/connected/*coverage.ec'
    ])
}

我尝试了 **/*View*.*' 的几种变体,包括 **/*View.*' 和其他... 有什么我忽略的地方吗?

您可以使用 filter on fileTree.

例如

src/main/java/View.java

class View {}

src/main/java/ViewModel.java

class ViewModel {}

src/main/java/Example.java

class Example {}

src/test/java/ExampleTest.java

import org.junit.Test;

public class ExampleTest {
    @Test
    public final void test() {
    }
}

build.gradle

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

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'junit:junit:4.13'
}

jacocoTestReport {
    classDirectories.setFrom(
        fileTree(dir: "build/classes/java/main")
            .filter({file -> !file.name.contains('View') || file.name.contains('ViewModel')})
    )
}

执行

gradle clean test jacocoTestReport

使用 Gradle 6.2.1 将在目录 build/reports/jacoco/test/html/ 中生成以下报告,该报告不包含 View,但包含 ViewModelExample :