我尝试使用Jacoco Gradle插件为我的PowerMockito单元测试获取代码覆盖率。我必须使用离线工具,因为PowerMockito不支持在线模式。
对于Jacoco,您必须创建Ant任务,这将使代码覆盖,但离线检测的所有示例都使用与&#不兼容的' Java' 插件39; com.android.library' 插件。
使用' 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
对于Android我使用
apply plugin: 'com.android.library'
此插件没有' 任务,' jacocoTestReport' 任务,并且具有不同的SourceSet实现。当我尝试使用这两个插件时出现此错误消息:
The 'java' plugin has been applied, but it is not compatible with the Android plugins
所以,我的问题是:如果在Android平台的情况下如何使用Gradle离线工具进行Gradle。