How to exclude some pakages from code coverage report using android and jacoco

1k Views Asked by At

I try to exclude some packages from the jacoco report but I don't find any documentation about doing that.

I tried that, but doesn't work:

testOptions {
    unitTests {
        jacoco {
            afterEvaluate {
                classDirectories.setFrom(files(classDirectories.files.collect {
                    fileTree(dir: it, exclude: '**/*databinding/**/*.*')
                }))
            }
        }
    }
}

I use com.android.tools.build:gradle:8.0.2 and org.jacoco:org.jacoco.core:0.8.8.

Do you know how to exclude packages from jacoco report?

2

There are 2 best solutions below

0
On

I don't find any "packaged" solution to solve my issue, so to move forward, I create my own gradle task:

task jacocoDebugUnitTestCoverageReport(type: JacocoReport, dependsOn: ['testDebugUnitTest']) {
    group = "Verification"
    description = "Creates JaCoCo test coverage report"
    reports {
        html.required = true
        xml.required = true
    }
    classDirectories.from = fileTree(
            dir: "$buildDir/intermediates/classes/debug/transformDebugClassesWithAsm/dirs/my/package/app",
            excludes: [
                    '**/databinding/*',
                    '**/Dagger*',
                    '**/Hilt*',
                    '**/DataBinding*',
                    '**/DataBinder*',
                    '**/*_*'
            ]
    )
    sourceDirectories.from = ['src/main/java/my.package.app']
    executionData.from = fileTree(
            dir: "$buildDir",
            includes: ["outputs/unit_test_code_coverage/debugUnitTest/testDebugUnitTest.exec"])
}

Running ./gradlew jacocoDebugUnitTestCoverageReport generate a coverage report without excluded packages.

If you know a better solution, I would appreciate your sharing.

0
On

Below is a gradle task with section afterEvaluate to exclude the package and all classes within from the test coverage evaluation. This is important to exclude the test coverage for classes which are data models or generated class

jacocoTestReport {
    reports {
        xml.required = true
    }

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