Skip to content

Instantly share code, notes, and snippets.

@danielgomezrico
Last active October 5, 2020 13:15
Show Gist options
  • Save danielgomezrico/36609a2204cc2f4e1201 to your computer and use it in GitHub Desktop.
Save danielgomezrico/36609a2204cc2f4e1201 to your computer and use it in GitHub Desktop.
Gradle - jacoco gradle file that is setup to run tests and create test coverage reports for Android (junit tests or connectedTests...). apply to your project and check "reporting" in gradle tasks. Thanks to https://github.com/artem-zinnatullin/qualitymatters for it.
project.afterEvaluate {
// Grab all build types and product flavors
def buildTypes = android.buildTypes.collect { type -> type.name }
def productFlavors = android.productFlavors.collect { flavor -> flavor.name }
// When no product flavors defined, use empty
if (!productFlavors) productFlavors.add('')
productFlavors.each { productFlavorName ->
buildTypes.each { buildTypeName ->
def sourceName, sourcePath
if (!productFlavorName) {
sourceName = sourcePath = "${buildTypeName}"
} else {
sourceName = "${productFlavorName}${buildTypeName.capitalize()}"
sourcePath = "${productFlavorName}/${buildTypeName}"
}
def testTaskName = "test${sourceName.capitalize()}UnitTest"
def coverageTaskName = "${testTaskName}Coverage"
if (project.tasks.findByName(testTaskName) == null) {
// If the task dont exists bc was disabled dont create the tasks
return
}
// Create coverage task of form 'testFlavorTypeCoverage' depending on 'testFlavorTypeUnitTest'
task "${coverageTaskName}"(type: JacocoReport, dependsOn: testTaskName) {
group = 'Reporting'
description = "Generate Jacoco coverage reports for the ${sourceName.capitalize()} build."
classDirectories = fileTree(dir: "${project.buildDir}/intermediates/classes/${sourcePath}",
excludes: ['**/R.class',
'**/R$*.class',
'**/*$ViewInjector*.*',
'**/*$ViewBinder*.*',
'**/BuildConfig.*',
'**/Manifest*.*',
'**/*$Lambda$*.*', // Jacoco can not handle several "$" in class name.
'**/*Module.*', // Modules for Dagger.
'**/*Dagger*.*', // Dagger auto-generated code.
'**/*MembersInjector*.*', // Dagger auto-generated code.
'**/*_Provide*Factory*.*'] // Dagger auto-generated code.
)
def coverageSourceDirs = ['src/main/java',
"src/$productFlavorName/java",
"src/$buildTypeName/java"]
additionalSourceDirs = files(coverageSourceDirs)
sourceDirectories = files(coverageSourceDirs)
executionData = files("${project.buildDir}/jacoco/${testTaskName}.exec")
reports {
xml.enabled = true
html.enabled = true
}
}
}
}
}
@danielgomezrico
Copy link
Author

Updated to create tasks for every submodule of the project.

@danielgomezrico
Copy link
Author

When a posible task configuration was disabled on modules dont create the task

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment