Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Jacoco setup to merge coverage for android when you run unit tests + integration tests and get a mixed result
// Merge of
// and
// Requires Jacoco plugin in build classpath.
apply plugin: 'jacoco'
jacoco {
toolVersion = "0.8.3"
// Enable test result in terminal
tasks.withType(Test) {
testLogging {
exceptionFormat "full"
events "skipped", "passed", "failed"
showStandardStreams true
jacoco.includeNoLocationClasses = true
variants().all { variant ->
def tag = "[jacoco.gradle]"
def variantName =
def variantCapName =
def fullTestTask = "testSuite${variantCapName}JacocoReport"
def unitTestTask = "test${variantCapName}UnitTest"
// use create<>CoverateReport since connectedCheck task does not generate jacoco reports so we
// need to depend on tasks that run tests + coverage
def instrumentedTestTask = "create${variantCapName}CoverageReport"
if (variantCapName == "Release") { "$tag ${} Task '$fullTestTask' is not enabled for Release builds."
if (project.tasks.findByName(unitTestTask) == null ||
project.tasks.findByName(instrumentedTestTask) ==
null) {
logger.warn "$tag ${} Task '$fullTestTask' was not created, you can enable it by passing -PcoverageEnabled or by setting testCoverageEnabled=true in setup."
task(fullTestTask, type: JacocoReport, dependsOn: [instrumentedTestTask, unitTestTask]) {
group = "Reporting"
description =
"Generate Jacoco coverage reports for $variantCapName Instrumented and UnitTest Tests"
onlyIf = { return true }
reports {
xml.enabled = true
html.enabled = true
csv.enabled = false
def androidFilter = ['**/R.class',
'**/*$Lambda$*.*', // Jacoco can not handle several "$" in class name.
'**/*Module.*', // Modules for Dagger.
'**/*Dagger*.*', // Dagger auto-generated code.
'**/*MembersInjector*.*', // Dagger auto-generated code.
'**/*_Factory.*', //Dagger auto-generated code
'**/*$*$*.*', // Anonymous classes generated by kotlin
//add libraries
//remove what we don't test
def librariesFilter = ['**/com/barista_v/**/*.*',
def fileFilter = androidFilter + librariesFilter
def classTree = fileTree(dir: variant.javaCompiler.destinationDir, excludes: fileFilter) +
fileTree(dir: "$buildDir/tmp/kotlin-classes/$variantName", excludes: fileFilter)
sourceDirectories = files(["src/main/java",
classDirectories = files([classTree])
executionData = fileTree(dir: "$buildDir",
includes: ["jacoco/test${variantCapName}UnitTest.exec",
doLast {
println "Custom $fullTestTask Jacoco task run for instrumented and unit-tests."
def variants() {
if ('libraryVariants')) {
} else {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment