I just integrated Jacoco code coverage for junit and UI test in my android studio project.
I added following steps:
In my app level build.gradle file:
apply plugin: 'jacoco'
and then added below code inside android { }
debug {
testCoverageEnabled = true
enableAndroidTestCoverage = true
enableUnitTestCoverage = true
}
and then added below code:
jacoco {
toolVersion = "0.8.8"
}
tasks.withType(Test).configureEach {
jacoco {
excludes = [
"**/R.class",
"**/R\$*.class",
"**/BuildConfig.*",
"**/Manifest*.*",
"**/*Test*.*"
]
}
}
android {
// Iterate over all application variants (e.g., debug, release)
applicationVariants.configureEach { variant ->
// Extract variant name and capitalize the first letter
def variantName = variant.name.capitalize()
// Define task names for unit tests and Android tests
def unitTests = "test${variantName}UnitTest"
def androidTests = "connected${variantName}AndroidTest"
// Register a JacocoReport task for code coverage analysis
tasks.register("Jacoco${variantName}CodeCoverage", JacocoReport) {
// Depend on unit tests and Android tests tasks
dependsOn(unitTests, androidTests)
// Set task grouping and description
group = "Reporting"
description = "Execute UI and unit tests, generate and combine Jacoco coverage report"
// Configure reports to generate both XML and HTML formats
reports {
xml.required = true
xml.outputLocation = layout.buildDirectory.file("jacoco/xml/${variantName}Coverage.xml")
html.required = true
html.outputLocation = layout.buildDirectory.dir("jacoco/html/${variantName}Coverage.html")
}
// Set source directories to the main source directory
sourceDirectories.setFrom(layout.projectDirectory.dir("src/main"))
// Set class directories to compiled Java and Kotlin classes, excluding specified exclusions
classDirectories.setFrom(files(
fileTree(dir: layout.buildDirectory.dir("intermediates/javac/")) {
exclude "**/R.class", "**/R\$*.class", "**/BuildConfig.*", "**/Manifest*.*", "**/*Test*.*"
},
fileTree(dir: layout.buildDirectory.dir("tmp/kotlin-classes/")) {
exclude "**/R.class", "**/R\$*.class", "**/BuildConfig.*", "**/Manifest*.*", "**/*Test*.*"
}
))
// Collect execution data from .exec and .ec files generated during test execution
executionData.setFrom(files(
fileTree(dir: layout.buildDirectory) { include "**/*.exec", "**/*.ec" }
))
}
}
}
But still code coverage report not generated in my android studio.