Powermock Jacoco Gradle Android项目的0%覆盖率

时间:2018-10-30 19:13:29

标签: android offline powermock jacoco instrumentation

我们有一个Android项目,我们在一些测试用例中使用Powermock,在覆盖率报告中使用Jacoco。我们注意到,我们的某些班级确实得到了 0%的覆盖率,尽管它们确实被覆盖了。我们还观察了以下有关受影响班级的消息。

"Classes ... do no match with execution data."

一些在线搜索显示Powermock and Jacoco don't play well离线检测是一种可能的解决方法。

以前有人用过gradle Offline Instrumentation脚本进行android项目吗?

1 个答案:

答案 0 :(得分:1)

事后看来,我想这可以通过足够的Android经验和在线阅读来解决。但是,当这一切落在我的腿上时,我(现在仍然)对Android,gradle和groovy还是比较陌生,所以我正在为下一个我写这个:-D

胡桃夹子中发生的事情摘自雅各博forum

  • 源文件被编译为非仪表类文件
  • 已检测非乐器类文件(可以离线预先插入乐器,也可以由Java代理在运行时自动插入)
  • 执行收集到exec文件中的检测类
  • 报告使用分析执行文件和原始非仪表类文件获得的信息来修饰源文件
  • 在报告生成过程中,
  • 消息“ Classes ... do no match with execution data. ”表示用于生成报告的类文件与检测之前的类不同。

解决方案

Jacoco Offline Instrumentation页提供了此摘录中脱机检测应执行的主要步骤:

  

对于此类情况,可以使用JaCoCo预先插入类文件,   例如仪器Ant任务。在运行时   预插装类需要放在类路径上,而不是   原始课程。此外,必须将jacocoagent.jar放在   类路径。

下面的脚本正是这样做的:

    apply plugin: 'jacoco'

configurations {
    jacocoAnt
    jacocoRuntime
}

jacoco {
    toolVersion = "0.8.1"
}

def offline_instrumented_outputDir = "$buildDir.path/intermediates/classes-instrumented/debug"

tasks.withType(Test) {
    jacoco.includeNoLocationClasses = true
}

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

task jacocoTestReport(type: JacocoReport, dependsOn: "test") {
    group = "Reporting"

    description = "Generate Jacoco coverage reports"

    classDirectories = fileTree(
            dir: 'build/intermediates/classes/debug',
            excludes: ['**/R.class',
                       '**/R$*.class',
                       '**/BuildConfig.*',
                       '**/MainActivity.*']
    )

    sourceDirectories = files(coverageSourceDirs)
    executionData = files('build/jacoco/testDebugUnitTest.exec')
}

jacocoTestReport {
    reports {
        xml.enabled  true
        html.enabled  true
        html.destination file("build/test-results/jacocoHtml")
    }
}

/* This task is used to create offline instrumentation of classes for on-the-fly instrumentation coverage tool like Jacoco. See jacoco classId
     * and Offline Instrumentation from the jacoco site for more info.
     *
     * In this case, some classes mocked using PowerMock were reported as 0% coverage on jacoco & Sonarqube. The issue between PowerMock and jacoco
     * is well documented, and a possible solution is offline Instrumentation (not so well documented for gradle).
     *
     * In a nutshell, this task:
     *  - Pre-instruments the original *.class files
     *  - Puts the instrumented classes path at the beginning of the task's classpath (for report purposes)
     *  - Runs test & generates a new exec file based on the pre-instrumented classes -- as opposed to on-the-fly instrumented class files generated by jacoco.
     *
     * It is currently not implemented to run prior to any other existing tasks (like test, jacocoTestReport, etc...), therefore, it should be called
     * explicitly if Offline Instrumentation report is needed.
     *
     *  Usage: gradle clean & gradle createOfflineInstrTestCoverageReport & gradle jacocoTestReport
     *   - gradle clean //To prevent influence from any previous task execution
     *   - gradle createOfflineInstrTestCoverageReport //To generate *.exec file from offline instrumented class
     *   - gradle jacocoTestReport //To generate html report from newly created *.exec task
     */
task createOfflineTestCoverageReport(dependsOn: ['instrument', 'testDebugUnitTest']) {
    doLast {
        ant.taskdef(name: 'report',
                classname: 'org.jacoco.ant.ReportTask',
                classpath: configurations.jacocoAnt.asPath)
        ant.report() {
            executiondata {
                ant.file(file: "$buildDir.path/jacoco/testDebugUnitTest.exec")
            }
            structure(name: 'Example') {
                classfiles {
                    fileset(dir: "$project.buildDir/intermediates/classes/debug")
                }
                sourcefiles {
                    fileset(dir: 'src/main/java')
                }
            }
            //Uncomment if we want the task to generate jacoco html reports. However, the current script does not exclude files.
            //An alternative is to used jacocoTestReport after this task finishes
            //html(destdir: "$buildDir.path/reports/jacocoHtml")
        }
    }
}

/*
 * Part of the Offline Instrumentation process is to add the jacoco runtime to the class path along with the path of the instrumented files.
 */
gradle.taskGraph.whenReady { graph ->
    if (graph.hasTask(instrument)) {
        tasks.withType(Test) {
            doFirst {
                systemProperty 'jacoco-agent.destfile', buildDir.path + '/jacoco/testDebugUnitTest.exec'
                classpath = files(offline_instrumented_outputDir) + classpath + configurations.jacocoRuntime
            }
        }
    }
}

/*
 *  Instruments the classes per se
 */
task instrument(dependsOn:'compileDebugUnitTestSources') {
    doLast {
        println 'Instrumenting classes'

        ant.taskdef(name: 'instrument',
                classname: 'org.jacoco.ant.InstrumentTask',
                classpath: configurations.jacocoAnt.asPath)

        ant.instrument(destdir: offline_instrumented_outputDir) {
            fileset(dir: "$buildDir.path/intermediates/classes/debug")
        }
    }
}

用法

  • 可以将脚本复制到单独的文件中。例如:jacoco.gradle

  • 参考build.gradle中的jacoco文件。例如:apply from: jacoco.gradle

  • 确保适当的依赖性:jacocoAnt 'org.jacoco:org.jacoco.ant:0.8.1:nodeps'

  • 在命令行中运行:gradle clean & gradle createOfflineTestCoverageReport & gradle jacocoTestReport

    gradle clean 将清除以前的gradle执行工件

    gradle createOfflineTestCoverageReport 将创建离线工具,更改类路径的顺序,生成.exec文件

    gradle jacocoTestReport 将运行测试并根据先前生成的.exec文件生成jacoco报告

迷失了?

我已经将github Jacoco Powermock Android项目与示例脚本放在一起,以重现并解决此问题。它还包含有关解决方案的更多信息。

参考

https://github.com/powermock/powermock/wiki/Code-coverage-with-JaCoCo
https://www.jacoco.org/jacoco/trunk/doc/classids.html
https://www.jacoco.org/jacoco/trunk/doc/offline.html
https://github.com/powermock/powermock-examples-maven/tree/master/jacoco-offline
https://automated-testing.info/t/jacoco-offline-instrumentations-for-android-gradle/20121
https://stackoverflow.com/questions/41370815/jacoco-offline-instrumentation-gradle-script/42238982#42238982
https://groups.google.com/forum/#!msg/jacoco/5IqM4AibmT8/-x5w4kU9BAAJ