我必须在我的项目中使用Jacoco离线工具,因为还使用了PowerMock。
问题描述:假设您具有两个模块Gradle项目:A,B。模块A
的测试涵盖了模块B
中的代码。在代码覆盖率数据收集中,我发现模块A
的覆盖率数据(应由模块B
提供)完全丢失。
我创建了一个演示该问题的测试项目:https://github.com/SurpSG/jacoco-offline-instrumentation
基于Gradle项目的Jacoco离线仪表安装程序基于答案https://stackoverflow.com/a/42238982/2689114
[另一方面,当我使用jacoco gradle插件时,我可以观察到模块A
为模块B
提供的覆盖率数据已成功收集到摘要报告中。我还创建了一个测试项目来证明这一点:https://github.com/SurpSG/jacoco-gradle-plugin-merge-coverage
我是否为gradle多模块项目+ jacoco离线检测设置错误?
经过一番调查,我发现Gradle中的模块依赖关系是通过.jar文件解决的:
<dependent-module>.classpath contains <dependency-module>.jar
因此,就我而言,我需要构建一些包含检测类的特殊jar。
乐器类
task preprocessClassesForJacoco(dependsOn: ['classes']) {
ext.outputDir = buildDir.path + '/classes-instrumented'
doLast {
ant.taskdef(name: 'instrument',
classname: 'org.jacoco.ant.InstrumentTask',
classpath: configurations.jacoco.asPath)
ant.instrument(destdir: outputDir) {
fileset(dir: sourceSets.main.java.outputDir, includes: '**/*.class', erroronmissingdir: false)
}
}
}
下一步将是建筑仪器罐:
task jacocoInstrumentedJar(type: Jar, dependsOn: [preprocessClassesForJacoco]) {
baseName "${project.name}-instrumented"
from preprocessClassesForJacoco.outputDir // path to instrumented classes
}
最后,我们需要替换常用的.jar 带工具一个
gradle.taskGraph.whenReady { graph ->
if (graph.hasTask(preprocessClassesForJacoco)) {
tasks.withType(Test) {
doFirst {
...
// getting a module dependencies
def modulesDependencies = moduleDependencies(project)
// removing regular jars
classpath -= files(modulesDependencies.jar.outputs.files)
// adding instrumented jars
classpath += files(modulesDependencies.jacocoInstrumentedJar.outputs.files)
}
}
}
}
我已经通过上述步骤更新了示例项目https://github.com/SurpSG/jacoco-offline-instrumentation。随时检查该项目以尝试。