Search code examples
androidunit-testinggradlejacocojacoco-plugin

JaCoCo Gradle - Exclude classes & override Includes


I am attempting to refine my code coverage in my project, and want to exclude any View classes (as they are not tested/testable) but include any ViewModel classes... but I can't seem to get the wildcard filters to cooperate, it's all or nothing!


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

I've tried several variations of **/*View*.*', including **/*View.*' and others... Is there something that I am overlooking?


Solution

  • You can use filter on fileTree.

    For example for

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

    and 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')})
        )
    }
    

    Execution of

    gradle clean test jacocoTestReport
    

    using Gradle 6.2.1 will generate the following report in directory build/reports/jacoco/test/html/ that doesn't contain View, but contains ViewModel and Example:

    report