本文针对已对在android studio上使用过jacoco统计代码覆盖率的开发者。如有不了解jacoco统计工程代码覆盖率情况,情看:http://www.jianshu.com/p/d9e67230dae8
目前就我的测试情况,AndroidTest的多项目工程代码覆盖率是可实现的,但是UnitTest仍然无法实现在主工程中统计所有子项目覆盖率
实现步骤:
1.依赖配置
1.1子项目(依赖项目)假设叫lib_project:
android {
...
defaultConfig {
//使用安卓集成环境测试,不影响juit
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
publishNonDefault true 默认以debug模式运行,一般用于子工程
// testOptions {//jacoco配置(解决有时代码覆盖率为0的问题)
// unitTests.all {
// jacoco {
// includeNoLocationClasses = true
// }
// }
// }
buildTypes {
debug {
//debug模式下生成代码覆盖率配置
testCoverageEnabled = true
}
release {testCoverageEnabled true}
}
}
1.2.主项目
android {
...
defaultConfig {
...
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
compileOptions {
sourceCompatibilityJavaVersion.VERSION_1_7
targetCompatibilityJavaVersion.VERSION_1_7
}
buildTypes {
release {
testCoverageEnabled true
}
debug {
testCoverageEnabled true
}
}
}
dependencies {
..
debugCompile project(path:': lib_project ',configuration: 'debug')
testCompile 'junit:junit:4.12'
androidTestCompile 'com.android.support.test:runner:0.4.1'
}
apply plugin: 'jacoco'
jacoco {
//版本过高可能出现could not read execution data 问题
toolVersion = "0.7.4+"
}
//下面核心代码,配置jacoco task
task jacocoTestReport(type: JacocoReport) {
//androidTest和Test分别测试完
group = "Reporting"
description = "Generate Jacoco coverage reports" // exclude auto-generated classes and tests
def fileFilter = ['**/R.class', '**/R$*.class','**/BuildConfig.*', '**/Manifest*.*','android/**/*.*']
def debugTree = fileTree(dir:"./build/intermediates/classes/debug",excludes: fileFilter)
sourceDirectories = files("src/main/java") //源码
classDirectories = files([debugTree]) //class字节码
project.rootProject.allprojects.each {project ->
//添加子工程源码和class字节码, 使用 "debug" 编译类型测试覆盖率
sourceDirectories += files((project.projectDir).toString() + "/src/main/java")
classDirectories += fileTree(dir: (project.projectDir).toString() + "/build/intermediates/classes/debug", excludes: fileFilter)
}
additionalSourceDirs = files("src/main/java")
executionData = fileTree(dir: "$buildDir", includes: [
"jacoco/testDebugUnitTest.exec",
"outputs/code-coverage/connected/coverage.ec" ])
reports {
xml.enabled = true
xml.destination = "${buildDir}/jacocoTestReport.xml"
csv.enabled = false
html.enabled = true
//报告生成处
html.destination = "${buildDir}/reports/jacoco"
}
}