apply plugin: 'jacoco' jacoco { // https://bintray.com/bintray/jcenter/org.jacoco:org.jacoco.core toolVersion = "0.8.5" } android { buildTypes { debug { testCoverageEnabled true } } testOptions { unitTests.all { jacoco { //some weird Java9 issue (https://github.com/gradle/gradle/issues/5184) includeNoLocationClasses = true excludes = ['jdk.internal.*'] } } } } project.afterEvaluate { if (project.plugins.hasPlugin('com.android.application')) { android.applicationVariants.all { variant -> def name = variant.name def testTaskName = "test${name.capitalize()}UnitTest" createJacocoReportTask(testTaskName, name) } } else if (project.plugins.hasPlugin('com.android.library')) { android.libraryVariants.all { variant -> def name = variant.name def testTaskName = "test${name.capitalize()}UnitTest" createJacocoReportTask(testTaskName, name) } } } private void createJacocoReportTask(testTaskName, name) { tasks.register("${testTaskName}Coverage", JacocoReport) { JacocoReport task -> task.dependsOn tasks.named("$testTaskName") task.group = "Reporting" task.description = "Generate Jacoco coverage reports for the ${name.capitalize()} build." task.additionalClassDirs(fileTree( dir: "${project.buildDir}/intermediates/javac/${name}", excludes: ['**/R.class', '**/R$*.class', 'android/**/*.class', '**/*$ViewInjector*.*', '**/*$ViewBinder*.*', '**/BuildConfig.*', '**/*$Lambda$*.*', '**/*Dagger*.*', 'android/**/*.*', '**/*$*$*.*', '**/Manifest*.*'])) task.additionalSourceDirs(files(["${project.projectDir}/src/main/java"])) task.executionData(files("${project.buildDir}/jacoco/${testTaskName}.exec")) task.reports { xml.enabled = true xml.destination = file("${project.buildDir}/jacoco/report/${testTaskName}Coverage.xml") html.enabled = true html.destination = file("${project.buildDir}/jacoco/report/html/${testTaskName}") } } }