Jacoco and Unit Tests Code Coverage with android-gradle-plugin >= 1.1

后端 未结 9 859

I recently started integrating android-gradle-plugin 1.1.0 in one of my projects. The project uses robolectric 2.4 to run unit tests.

It\'s

9条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-12 21:26

    I was finally able to see my code coverage of JUnit tests with Android Studio 1.1.

    jacoco.gradle

    apply plugin: 'jacoco'
    
    jacoco {
        toolVersion "0.7.1.201405082137"
    }
    
    def coverageSourceDirs = [
            "$projectDir/src/main/java",
    ]
    
    task jacocoTestReport(type: JacocoReport, dependsOn: "testDebug") {
        group = "Reporting"
        description = "Generate Jacoco coverage reports after running tests."
        reports {
            xml.enabled = true
            html.enabled = true
        }
        classDirectories = fileTree(
                dir: './build/intermediates/classes/debug',
                excludes: ['**/R*.class',
                           '**/*$InjectAdapter.class',
                           '**/*$ModuleAdapter.class',
                           '**/*$ViewInjector*.class'
                ]
        )
        sourceDirectories = files(coverageSourceDirs)
        executionData = files("$buildDir/jacoco/testDebug.exec")
        // Bit hacky but fixes https://code.google.com/p/android/issues/detail?id=69174.
        // We iterate through the compiled .class tree and rename $$ to $.
        doFirst {
            new File("$buildDir/intermediates/classes/").eachFileRecurse { file ->
                if (file.name.contains('$$')) {
                    file.renameTo(file.path.replace('$$', '$'))
                }
            }
        }
    }
    

    and then within the build.gradle file of the module (I put it between android and dependencies):

    apply from: '../jacoco.gradle'
    

    Also in the defaultConfig block of android. I've added this (don't know if it is necessary, but I've got this from this blog):

    android {
        defaultConfig {
            testHandleProfiling true
            testFunctionalTest true
        }
    }
    

    Enjoy.

提交回复
热议问题