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

问题描述 投票:2回答:2

我想要的是:

我想在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 gradle android-gradle build.gradle jacoco
2个回答
0
投票

首先检查gradle版本:对于同样应用Java插件的项目,JaCoCo插件会自动添加以下任务:

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

gradle 3.5(jacocoTestReport,jacocoTestCoverage验证任务)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']
)}
...

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

© www.soinside.com 2019 - 2024. All rights reserved.