Android使用jacocoTestCoverageVerification检查代码覆盖率阈值

时间:2017-05-02 11:13:22

标签: android gradle android-gradle build.gradle jacoco

我想要的是什么:

我想在Android gradle中将代码覆盖率阈值与最小值匹配,例如60%等。

我尝试了什么

stack overflow question i have looked into

jacoco plugin gradle

我正面临的问题

My Gradle文件的编写方式如下:

apply plugin: 'com.android.application'

apply plugin: 'jacoco'


jacoco {
    toolVersion = "0.7.6.201602180812"

    reportsDir = file("$buildDir/customJacocoReportDir")
}

def coverageSourceDirs = [
        'src/main/java',
]

jacocoTestReport {

reports {

        xml.enabled false
        csv.enabled false
        html.destination "${buildDir}/jacocoHtml"
    }
}



jacocoTestCoverageVerification {

    violationRules {
        rule {
            limit {
                minimum = 0.5
            }
        }

        rule {
            enabled = false
            element = 'CLASS'
            includes = ['org.gradle.*']

            limit {
                counter = 'LINE'
                value = 'TOTALCOUNT'
                maximum = 0.3
            }
        }
    }
}

现在,当我同步我的gradle文件时,我面对错误

无法在类型为org.gradle.api.Project的项目':app'上找到参数[build_5t0t9b9hth6zfihsyl5q2obv8 $ _run_closure2 @ 41a69b20]的方法jacocoTestReport()。

如果我评论jacocoTestReport任务,那么

无法在类型为org.gradle.api.Project的项目':app'上找到参数[build_5t0t9b9hth6zfihsyl5q2obv8 $ _run_closure2 @ 3da790a8]的方法jacocoTestCoverageVerification()。

我无法理解这里到底发生了什么。为什么jacocoTestCoverageVerification方法不在插件中。我做错了什么。

gradle是从android插件中选择jacoco插件吗?

我已经尝试过将jacoco的版本提到0.6.3,正如文档中提到的那样,jacocoTestCoverageVerification方法是在这个版本之上编写的。

如果有人能解决这个问题,那将非常有帮助。

请告诉我所需的任何其他信息。

由于

2 个答案:

答案 0 :(得分:0)

首先检查你的gradle verison: 对于也应用Java插件的项目,JaCoCo插件会自动添加以下任务:

gradle 3.3(jacocoTestReport任务) https://docs.gradle.org/3.3/userguide/jacoco_plugin.html#sec:jacoco_tasks

gradle 3.5(jacocoTestReport,jacocoTestCoverageVerification任务) https://docs.gradle.org/current/userguide/jacoco_plugin.html#sec:jacoco_tasks

对于早期版本的gradle,您需要添加jacoco依赖项:

...
dependencies {
сlasspath (
[group: 'org.jacoco', name: 'org.jacoco.agent', version: version: '0.7.7.201606060606'],
[group: 'org.jacoco', name: 'org.jacoco.ant', version: version: '0.7.7.201606060606']
)}
...

答案 1 :(得分:0)

每次关键字 android jacocoTestCoverageVerification 引导我到此页面时,此问题一直困扰着我几次,但没有任何答案。最后,我成功地使jacoco正常运行,并且我想在这里分享我的解决方案。

gradle找不到jacocoTestCoverageVerification和jacocoTestReport的原因是因为For projects that also apply the Java Plugin, the JaCoCo plugin automatically adds the following tasks jacocoTestReport and jacocoTestCoverageVerification。 这意味着对于未应用Java插件的项目,它不会添加jacocoTestReport和jacocoTestCoverageVerification。

所以我们必须自己添加它们。

点击链接Code Coverage for Android Testing,我们可以添加任务jacocoTestReport。

并且,我们还可以添加任务jacocoTestCoverageVerification。

全功能就像

// https://engineering.rallyhealth.com/android/code-coverage/testing/2018/06/04/android-code-coverage.html
ext.enableJacoco = { Project project, String variant ->
    project.plugins.apply('jacoco')

    final capVariant = variant.capitalize()

    StringBuilder folderSb = new StringBuilder(variant.length() + 1)
    for (int i = 0; i < variant.length(); i++) {
        char c = variant.charAt(i)
        if (Character.isUpperCase(c)) {
            folderSb.append('/')
            folderSb.append(Character.toLowerCase(c))
        } else {
            folderSb.append(c)
        }
    }
    final folder = folderSb.toString()


    project.android {
        buildTypes {
            debug {
                testCoverageEnabled true
            }
        }

        testOptions {
            unitTests.all {
                jacoco {
                    //You may encounter an issue while getting test coverage for Robolectric tests.
                    //To include Robolectric tests in the Jacoco report, one will need to set the includeNolocationClasses flag to true.
                    // This can no longer be configured using the android DSL block, thus we search all tasks of Test type and enable it

                    includeNoLocationClasses = true
                }
            }
        }
        jacoco {
            version = '0.8.1'
        }
    }

    project.jacoco {
        toolVersion = '0.8.1'
    }

    project.tasks.create(
            name: 'jacocoTestCoverageVerification',
            type: JacocoCoverageVerification,
            dependsOn: ["test${capVariant}UnitTest",
                        "create${capVariant}CoverageReport"
            ]
    ) {
        onlyIf = {
            true
        }

        violationRules {
            rule {
                limit {
                    minimum = 0.5
                }
            }

            rule {
                enabled = false
                element = 'CLASS'
                includes = ['org.gradle.*']

                limit {
                    counter = 'LINE'
                    value = 'TOTALCOUNT'
                    maximum = 0.3
                }
            }
        }
        def coverageSourceDirs = [
                "src/main/java",
                "src/main/kotlin"
        ]

        def fileFilter = [
                '**/R.class',
                '**/R$*.class',
                '**/*$ViewInjector*.*',
                '**/*$ViewBinder*.*',
                '**/BuildConfig.*',
                '**/*_MembersInjector.class',
                '**/Dagger*Component.class',
                '**/Dagger*Component$Builder.class',
                '**/*Module_*Factory.class',
                '**/*_MembersInjector.class',
                '**/Dagger*Subcomponent*.class',
                '**/*Subcomponent$Builder.class',
                '**/Manifest*.*'
        ]

        def javaClasses = fileTree(
                dir: "${project.buildDir}/intermediates/javac/$folder",
                excludes: fileFilter
        )
        def kotlinClasses = fileTree(
                dir: "${project.buildDir}/tmp/kotlin-classes/$variant",
                excludes: fileFilter
        )

        group = "Reporting"
        description = "Applying Jacoco coverage verification for the ${project.name} with the " +
                "$variant variant."
        classDirectories = files([javaClasses], [kotlinClasses])
        additionalSourceDirs = files(coverageSourceDirs)
        sourceDirectories = files(coverageSourceDirs)
        executionData = fileTree(dir: "${project.buildDir}", includes: [
                "jacoco/testDebugUnitTest.exec",
                "outputs/code_coverage/debugAndroidTest/connected/*.ec",
                "outputs/code_coverage/connected/*.ec" //Check this path or update to relevant path
        ])
    }
    project.tasks.create(
            name: 'jacocoTestReport',
            type: JacocoReport,
            dependsOn: ["test${capVariant}UnitTest",
                        "create${capVariant}CoverageReport"
            ]
    ) {
        def coverageSourceDirs = [
                "src/main/java",
                "src/main/kotlin"
        ]

        def fileFilter = [
                '**/R.class',
                '**/R$*.class',
                '**/*$ViewInjector*.*',
                '**/*$ViewBinder*.*',
                '**/BuildConfig.*',
                '**/*_MembersInjector.class',
                '**/Dagger*Component.class',
                '**/Dagger*Component$Builder.class',
                '**/*Module_*Factory.class',
                '**/*_MembersInjector.class',
                '**/Dagger*Subcomponent*.class',
                '**/*Subcomponent$Builder.class',
                '**/Manifest*.*'
        ]

        def javaClasses = fileTree(
                dir: "${project.buildDir}/intermediates/javac/$folder",
                excludes: fileFilter
        )
        def kotlinClasses = fileTree(
                dir: "${project.buildDir}/tmp/kotlin-classes/$variant",
                excludes: fileFilter
        )

        group = "Reporting"
        description = "Generate Jacoco coverage reports for the ${project.name} with the " +
                "$variant variant."
        classDirectories = files([javaClasses], [kotlinClasses])
        additionalSourceDirs = files(coverageSourceDirs)
        sourceDirectories = files(coverageSourceDirs)
        executionData = fileTree(dir: "${project.buildDir}", includes: [
                "jacoco/testDebugUnitTest.exec",
                "outputs/code_coverage/debugAndroidTest/connected/*.ec",
                "outputs/code_coverage/connected/*.ec" //Check this path or update to relevant path
        ])
        onlyIf = {
            true
        }
        println project
        println "current $project buildDir: $buildDir project buildDir: ${project.buildDir}"
        System.out.flush()
        reports {
            html.enabled = true
            html.destination file("reporting/jacocohtml")
        }
    }


}

Gist version