我正在尝试使用Jacoco Gradle插件为我的PowerMockito单元测试获取代码覆盖率 . 我必须使用离线检测,因为PowerMockito不支持在线模式 .

对于Jacoco,您必须创建Ant任务,这将使代码覆盖,但离线检测的所有示例都使用与 'com.android.library' 插件不兼容的 'Java' 插件 .

使用'Java'插件的可行解决方案:

apply plugin: 'java'
apply plugin: 'jacoco'

//Additional SourceSets can be added to the jacocoOfflineSourceSets as needed by 
project.ext.jacocoOfflineSourceSets = [ 'main' ]
task doJacocoOfflineInstrumentation(dependsOn: [ classes, project.configurations.jacocoAnt ]) {
    inputs.files classes.outputs.files
    File outputDir = new File(project.buildDir, 'instrumentedClasses')
    outputs.dir outputDir
    doFirst {
        project.delete(outputDir)
        ant.taskdef(
            resource: 'org/jacoco/ant/antlib.xml',
            classpath: project.configurations.jacocoAnt.asPath,
            uri: 'jacoco'
        )
        def instrumented = false
        jacocoOfflineSourceSets.each { sourceSetName ->
            if (file(sourceSets[sourceSetName].output.classesDir).exists()) {
                def instrumentedClassedDir = "${outputDir}/${sourceSetName}"
                ant.'jacoco:instrument'(destdir: instrumentedClassedDir) {
                    fileset(dir: sourceSets[sourceSetName].output.classesDir, includes: '**/*.class')
                }
                //Replace the classes dir in the test classpath with the instrumented one
                sourceSets.test.runtimeClasspath -= files(sourceSets[sourceSetName].output.classesDir)
                sourceSets.test.runtimeClasspath += files(instrumentedClassedDir)
                instrumented = true
            }
        }
        if (instrumented) {
            //Disable class verification based on https://github.com/jayway/powermock/issues/375
            test.jvmArgs += '-noverify'
        }
    }
}
test.dependsOn doJacocoOfflineInstrumentation

Jacoco offline instrumentation Gradle script

jacoco code coverage report generator showing error : "Classes in bundle 'Code Coverage Report' do no match with execution data"

对于我使用的Android

apply plugin: 'com.android.library'

而且这个插件没有 'classes' 任务, 'jacocoTestReport' 任务并且具有不同的SourceSet实现 . 当我尝试使用这两个插件时出现此错误消息:

The 'java' plugin has been applied, but it is not compatible with the Android plugins

所以,我的问题是:如果在Android平台的情况下如何使用Jacoco离线工具进行Gradle .