jacocoTestCoverageVerification

jacocoTestCoverageVerification

我想要什么:

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

我尝试过的

stack overflow question i have looked into

jacoco plugin gradle

我面临的问题

我的 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 方法写在这个版本之上。

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

让我知道任何其他需要的信息。

谢谢

最佳答案

这个问题一直困扰着我几次,每次关键字 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 Plugin 的项目, 不会 添加 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

关于Android 使用 jacocoTestCoverageVerification 检查代码覆盖率阈值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43736464/

10-11 22:14