如何获得Android中的仪器测试的代码覆盖率

时间:2019-08-27 11:49:59

标签: android android-studio

在Android Studio中,对于在androidTest文件夹下编写的工具测试,我没有找到“以代码覆盖率运行”选项。但是,对于在测试文件夹中编写的JUnit测试用例,我可以看到它。

有人可以告诉我如何获得该报道吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

因此,根据您的评论,我认为您已成功在gradle中设置了jacoco。现在,请在您的 app gradle中更改或添加以下材料:

coveralls {
    jacocoReportPath = "${buildDir}/reports/coverage/debug/report.xml"
}

上面的代码使您的覆盖率报告在 app / build / report /..中,您将获得两个文件夹,包括另一个文件夹。 AndroidTest和测试文件夹。在AndroidTest文件夹中,您获得 coverage 文件夹并浏览 index.html ,您将获得仪器测试结果的覆盖率报告。与 tests 文件夹相同,对其进行浏览并浏览 index.html

现在是主要部分。您必须在 pp gradle

中编写以下代码
task jacocoTestReport(type: JacocoReport, dependsOn: ['testDebugUnitTest','connectedAndroidTest']) {

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

    // The lines below make sure we can report against Kotlin and exclude some Android Stuff
    def fileFilter = [
            '**/R.class', '**/R$*.class', '**/BuildConfig.*', '**/Manifest*.*',
            '**/*Test*.*', 'android/**/*.*'
    ]
    def debugTree = fileTree(dir: "$project.buildDir/intermediates/javac/debug/compileDebugJavaWithJavac/classes/", excludes: fileFilter)
    def mainSrc = "$project.projectDir/src/main/java"

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

成功同步后,您会在任务jacocoTestRepor ... 旁边看到一个播放按钮,将其选中并选择第一个,如“运行yourProject [jacoco]

”。