【android测试】jacoco做功能测试代码覆盖率统计

来源:互联网 发布:网络信息安全应急演练 编辑:程序博客网 时间:2024/04/29 00:08

1、新建test pkg

2、InstrumentedActivity要继承Main Activity


 

3、增加声明和申请权限


Manifest中增加:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

<instrumentation
   
android:name="com.xyy.jacoco.test.JacocoInstrumentation"
   
android:handleProfiling="true"
   
android:label="CoverageInstrumentation"
   
android:targetPackage="com.xyy.jacoco"
/>

 

Application中增加:

<activity
   
android:name=".test.InstrumentedActivity"
   
android:label="InstrumentationActivity"
/>

 

4、build.gradle中增加jacoco的插件和开关

使用插件

apply plugin: 'jacoco'

 

使用开关

debug {
    testCoverageEnabled = true
}

 

 

5、编译成debug包

6、确保我们写的instrumentation已经在设备上正确安装

adb shell pm list instrumentation

 

7、通过adb shell am instrument命令调起app

adb shell am instrumentcom.xyy.jacoco/com.xyy.jacoco.test.JacocoInstrumentation

 

adb logcat |findstr JacocoInstrumentation  //查看JacocoInstrumentation.java输出的日志,便于定位

8、操作手机,进行功能测试

9、生成coverage.ec文件

测试完成后,点击返回键退出app,将生成coverage.ec文件

/data/data/<yourPackageName>/files/coverage.ec

 

10、coverage.ec文件发到对应目录

coverage.ec放入app根目录/build/outputs/code-coverage/connected

11、修改build.gradle文件,增加以下代码在底部

def coverageSourceDirs = [
        '../app/src/main/java'
]
task jacocoTestReport(type: JacocoReport) {
    group = "Reporting"
   
description = "Generate Jacoco coverage reports after runningtests."
   
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/outputs/code-coverage/connected/coverage.ec")

    doFirst {
        new File("$buildDir/intermediates/classes/").eachFileRecurse { file ->
            if (file.name.contains('$$')) {
                file.renameTo(file.path.replace('$$','$'))
            }
        }
    }

12、在app的项目目录下执行gradle jacocoTestReport

 

13、查看覆盖率html报告

执行完gradle jacocoTestReport后,我们可以在app\build\reports\jacoco\jacocoTestReport\html目录下看到html报告。

index.html拖到浏览器中,可以看到具体的覆盖率数据啦。


原创粉丝点击