JaCoCo

Posted on By ᵇᵒ

JaCoCo Java Code Coverage Library

一个用于统计单元测试覆盖率的库,该库文档相当不友好。整合了个 jacoco.gradle 脚本:

apply plugin: 'jacoco'

jacoco {
    // JaCoCo 版本
    toolVersion = "0.8.7"
}

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

    reports {
        // 启用的报告文件格式
        xml.enabled = true
        html.enabled = true
    }

    // 忽略统计的 class,可根据需求自行增删
    def fileFilter = ['**/R*.class',
                      '**/R$*.class',
                      '**/*$InjectAdapter.class',
                      '**/*$ModuleAdapter.class',
                      '**/*$ViewInjector*.*',
                      '**/*$BuildConfig.*',
                      '**/*$Manifest*.*',
                      'androidx/**/*.*',
                      '**/databinding/*.*',
                      '**/data/*.*',
                      '**/generated/callback/*.*',
                      '**/lambda$*.class',
                      '**/lambda.class',
                      '**/*lambda.class',
                      '**/*lambda*.class']

    def javaSourceClasses = "$buildDir/intermediates/javac/debug/classes"
    def kotlinSourceClasses = "$buildDir/tmp/kotlin-classes/debug"
    def javaTree = fileTree(dir: javaSourceClasses, excludes: fileFilter)
    def kotlinTree = fileTree(dir: kotlinSourceClasses, excludes: fileFilter)
    getClassDirectories().setFrom(javaTree, kotlinTree)

    def sourceDirs = ["$projectDir/src/main/java"]
    getSourceDirectories().setFrom(files(sourceDirs))
    getAdditionalSourceDirs().setFrom(files(sourceDirs))

    getExecutionData().setFrom(files("$buildDir/jacoco/testDebugUnitTest.exec"))
}

拷贝该脚本至工程根目录下,在对应 android module 的 build.gradle 里 apply from: "${rootDir}/jacoco.gradle" ,然后设置 debug buildType testCoverageEnabled = true 即可:

    buildTypes {
        debug {
            testCoverageEnabled = true
            ···
        }
        release {
            ···
        }
    }

使用方式:gradle clean jacocoTestReport,或者在 Android Studio 右侧边栏找到 Gradle -> Tasks -> jacoco -> jacocoTestReport 双击执行。