您的位置:首页 > 移动开发 > Android开发

android+jacoco多模块项目中统计子模块代码覆盖率

2018-03-22 17:50 441 查看
上一次做了单项目的代码覆盖率统计,但是在实际的项目中,都是已模块开发为主。
研究了一下怎么去统计子模块中的代码覆盖率。
整体思路:1:既然是多模块的代码覆盖率统计,所以子模块必须也要是用jacoco插桩的方式打开子模块代码覆盖率统计开关;
2:处理子模块与主模块的依赖关系,使子模块也要用debug的方式打包(android正常打包是以release方式);
3:生成jacoco报告。
代码模块结构:


实践:一:插桩1、子模块插桩:
每个模块都需要添加gradle 所以写一个通用的gradle进行插桩
公用的gradle代码:
apply plugin: 'jacoco'
android {
publishNonDefault true
// defaultPublishConfig "debug"
buildTypes {
debug{
/**打开覆盖率统计开关**/
testCoverageEnabled = true
}
}
}


然后在每个需要插桩的子模块中添加公用的gradle:
我这里是(一定要放在library的后面,否则可能会报错):apply from: '../gradleCommon/build.gradle'


2、主模块(app):
    主模块没有添加公用的 ,看自己的情况而定吧。
二:子模块的依赖关系    我们需要将所有的依赖项从: 
compile project(':sharemodule')
的形式改变为 
debugCompile project(path:':sharemodule',configuration:'debug')
        当你把所有的子模块的依赖都用debugCompile方式时,可能会让app中的主类报错,这是因为有的项目中app的主类是继承了子类中的主类,需要将这个依赖改回compile方式依赖就行。



到这里就可以用gradle中的installDebug 安装app 并用命令启动,开始测试( 可参考上一篇文章),
adb shell am instrument 项目名称/com.xx.xx.xx.JacocoInstrumentation (JacocoInstrumentation 具体路径)

结束测试后拿到ec文件。
根据参考的博客jacocoagent.jar包重复的问题,这个一直没找到好的方法,我这边采用了在写一个公用的gradle 里面只有一句话:
android {
publishNonDefault true
}


当需要生成报告时,只需要注解掉build.gradle中的代码即可。
在app中的gradle添加如下代码:
task jacocoTestReport(type: JacocoReport) {
group = "Reporting"
description = "Generate Jacoco coverage reports after running tests."

reports {
xml.enabled true
html.enabled true
}

def excludesFilter = ['**/R.class',
'**/R$*.class',
'**/*$ViewInjector*.*',
'**/BuildConfig.*',
'**/Manifest*.*',]

sourceDirectories = files("src")
classDirectories = fileTree(dir: "./build/intermediates/classes/debug", excludes: excludesFilter)
project.rootProject.allprojects.each { project ->
if (project.name != "shell_en_agile" && project.name != "DolphinRecordTest" && project.name != "DolphinBrowserEN") {
sourceDirectories += files((project.projectDir).toString() + "/src")
classDirectories += fileTree(dir: (project.projectDir).toString() + "/build/intermediates/classes/debug", excludes: excludesFilter)
}
}

executionData = fileTree(dir: "$buildDir/outputs/coverage.ec") //需要修改
}        先在gradle里面执行createDebugCoverageReport 在app/build/outputs里面生成code-coverage文件将code-coverage/connected里面原始的ec文件删除,并加入刚才生成的coverage.ec文件。
执行gradle jacocoTestReport 生成报告。
有的地方说的不是很明白 看看参考博文吧。
参考:http://blog.csdn.net/cyanolive1/article/details/51782379
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: