Neal Sanche
Neal Sanche

Reputation: 1626

How can I configure the Code Coverage reports in Android Studio 2.3?

I've been running my code coverage reports on my Android project using Gradle at the command-line, using the following command:

./gradlew createDebugCoverageReport

This works, and produces a report that contains pretty much every package in my entire project, including third-party libraries. I'd like to configure the coverage reports to provide information about only my code. How do I set up the code paths, includes and excludes on the Jacoco reports in the built-in coverage reports being produced by the Android Studio toolchain?

I am not including any Jacoco plugins within my build scripts, I have simply added testCoverageEnabled true in my debug buildType.

Thanks!

Upvotes: 4

Views: 6163

Answers (1)

Jared Burrows
Jared Burrows

Reputation: 55517

You want to do the following:

  1. Run unit tests: gradlew testDebug
  2. Run android tests: gradlew connectedDebugAndroidTest
  3. Create code coverage for Android tests: gradlew createDebugCoverageReport
  4. After these steps, you can finally combine them using a single task

Apply testCoverageEnabled:

android {

    buildTypes {
        debug {
            testCoverageEnabled true
        }
    }

}

Apply includeNoLocationClasses:

android {

    testOptions {
        unitTests.all {
            jacoco {
                includeNoLocationClasses = true
            }
        }
    }

}

Now you can create a task like this one:

apply plugin: 'jacoco'

task jacocoTestReport(type: JacocoReport, dependsOn: ['testDebugUnitTest', 'createDebugCoverageReport']) {

    reports {
        xml.enabled = true
        html.enabled = true
    }

    def fileFilter = ['**/R.class', '**/R$*.class', '**/BuildConfig.*', '**/Manifest*.*', '**/*Test*.*', 'android/**/*.*']
    def debugTree = fileTree(dir: "${buildDir}/intermediates/classes/debug", excludes: fileFilter)
    def mainSrc = "${project.projectDir}/src/main/java"

    sourceDirectories = files([mainSrc])
    classDirectories = files([debugTree])
    executionData = fileTree(dir: "$buildDir", includes: [
            "jacoco/testDebugUnitTest.exec", 
            "outputs/code-coverage/connected/*coverage.ec"
    ])
}

And run it:

gradle clean jacocoTestReport

Source: https://medium.com/@rafael_toledo/setting-up-an-unified-coverage-report-in-android-with-jacoco-robolectric-and-espresso-ffe239aaf3fa

Upvotes: 7

Related Questions