# Jacoco offline instrumentation in gradle

**URL:** <https://discuss.gradle.org/t/jacoco-offline-instrumentation-in-gradle/9996>\
**Category:** Help/Discuss\
**Tags:** plugins\
**Created:** [June 8, 2015, 7:52am UTC](https://discuss.gradle.org/t/jacoco-offline-instrumentation-in-gradle/9996 "2015-06-08T07:52:59Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![datallah](https://avatars.discourse-cdn.com/v4/letter/d/f9ae1b/32.png) [@datallah](https://discuss.gradle.org/u/datallah)\
**Post date:** [October 14, 2016, 9:40pm UTC](https://discuss.gradle.org/t/jacoco-offline-instrumentation-in-gradle/9996/2 "2016-10-14T21:40:55Z")

</div>

I had a need to do this too and was able to figure out how to hack the jacoco plugin to do offline instrumentation:

```
//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
```

---

_[View the full topic](https://discuss.gradle.org/t/jacoco-offline-instrumentation-in-gradle/9996)._
