Jacoco配置代码如下:
apply plugin: 'jacoco'
tasks.withType(Test) {
jacoco.includeNoLocationClasses = true
}
ext {
getFileFilter = { ->
def jacocoSkipClasses = null
if (project.hasProperty('jacocoSkipClasses')) {
jacocoSkipClasses = project.property('jacocoSkipClasses')
}
//忽略类文件配置
def fileFilter = ['**/R.class', '**/R$*.class', '**/BuildConfig.*', '**/Manifest*.*', '**/*$ViewInjector*.*']
if (jacocoSkipClasses != null) {
fileFilter.addAll(jacocoSkipClasses)
}
return fileFilter
}
}
task jacocoTestReport(type: JacocoReport, dependsOn: ['testCoverageDebugUnitTest', 'createCoverageDebugCoverageReport']) {
group = "Reporting"
description = "Generate Jacoco coverage reports"
reports {
xml {
enabled = true
xml.destination file("build/reports/jacoco/jacoco.xml")
}
html {
enabled = true
html.destination file("build/reports/jacoco")
}
}
def fileFilter = project.getFileFilter()
//检测覆盖率的class所在目录(以项目class所在目录为准)
//gradle2.3 class所在目录
def coverageDebugTree = fileTree(dir: "$project.buildDir/intermediates/classes/coverageDebug", excludes: fileFilter)
//gradle3.2 class所在目录
def coverageDebugTreeNewGradle = fileTree(dir: "$project.buildDir/intermediates/javac/debug/compileDebugJavaWithJavac/classes", excludes: fileFilter)
def mainSrc = "$project.projectDir/src/main/java"
//设置需要检测覆盖率的目录
sourceDirectories = files([mainSrc])
//兼容gradle版本
classDirectories = files([coverageDebugTree, coverageDebugTreeNewGradle])
//以下路径也需要检查
executionData = fileTree(dir: project.buildDir, includes: [
'jacoco/testCoverageDebugUnitTest.exec', 'outputs/code-coverage/debugAndroidTest/connected/coverage.ec'
])
}
问题1:
Cannot set the value of read-only property ‘classDirectories’ for task ‘:app:testNameOfMyFlavorDebugUnitTestCoverage’ of type org.gradle.testing.jacoco.tasks.JacocoReport.
这是因为gradle版本不兼容的问题,将上述代码中文件获取由“=”改为.setFrom()。
示例 :sourceDirectories = files([mainSrc]) 改为 sourceDirectories.setfrom(files([mainSrc]))
问题2: Cannot set the value of read-only property ‘sourceDirectories’ for task ':app
这是依赖为引入的问题,解决方案是在项目的build.gradle中添加allprojects
allprojects {
repositories {
google()
mavenCentral()
}
}
问题3: java.lang.NoClassDefFoundError: jdk/internal/reflect/GeneratedSerializationConstructorAccessor1
找不到类,解决方案就是将这个包去掉。
jacoco.excludes = ['jdk.internal.*']
问题4:
An exception occurred applying plugin request [id: ‘com.android.application‘]
Failed to apply plugin 'com.android.internal.application'.
The option 'android.enableUnitTestBinaryResource' is deprecated.
The current default is 'false'
如下解决:
将本机gradle的配置文件,gradle.properties.中的
#android.enableUnitTestBinaryResources=true 注释掉
版权归原作者 韩~晓强 所有, 如有侵权,请联系我们删除。