I'm trying to get code coverage for my PowerMockito unit tests with Jacoco Gradle plugin. I have to use offline instrumentation because PowerMockito doesn't support online mode.
For Jacoco you have to create Ant task which will make code coverage, but all examples of offline instrumentation use 'Java' plugin which is not compatible with 'com.android.library' plugin.
Workable solutions which use 'Java' plugin:
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
For Android I use
apply plugin: 'com.android.library'
And this plugin doesn't have 'classes' task, 'jacocoTestReport' task and have different SourceSet implementation. This error message appears when I try to use both plugins:
The 'java' plugin has been applied, but it is not compatible with the Android plugins
So, my question is: How to use Jacoco offline instrumentation for Gradle in case of Android platform.