【android測試】jacoco做功能測試程式碼覆蓋率統計
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=
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拖到瀏覽器中,可以看到具體的覆蓋率資料啦。