这里是 Java 8 和 Gradle 4.6。我正在尝试配置我的 Gradle 构建以使用 Jacoco Plugin 但遇到一些困难。我已经让它与 Checkstyle 和 Findbugs 一起使用,这样运行
./gradlew clean build
就会调用 Checkstyle 和 Findbugs 任务,因为它们是 check
任务的依赖项。
我现在正在努力让 Jacoco 工作:
com.me.myapp.domain.model
包裹及其所有内容;和build/
目录下生成HTML版本的Jacoco报告;和./gradlew clean build
来让Jacoco像这样工作迄今为止我最好的尝试:
plugins {
id 'java-library'
id 'checkstyle'
id 'findbugs'
id 'jacoco'
}
dependencies {
compile(
'org.hibernate:hibernate-core:5.0.12.Final'
,'com.fasterxml.jackson.core:jackson-core:2.8.10'
,'com.fasterxml.jackson.core:jackson-databind:2.8.10'
,'com.fasterxml.jackson.core:jackson-annotations:2.8.0'
)
testCompile(
'junit:junit:4.12'
)
}
repositories {
jcenter()
mavenCentral()
}
checkstyle {
config = rootProject.resources.text.fromFile('buildConfig/checkstyle/checkstyle.xml')
toolVersion = '8.11'
}
tasks.withType(FindBugs) {
reports {
xml.enabled false
html.enabled true
}
}
findbugs {
excludeFilter = file('buildConfig/findbugs/findbugs-exclude.xml')
}
jacocoTestReport {
reports {
xml.enabled false
csv.enabled false
html.enabled true
}
afterEvaluate {
classDirectories = files(classDirectories.files.collect {
fileTree(dir: it,
exclude: [
'com/me/myapp/domain/model/**'
]
)
})
}
}
jacocoTestCoverageVerification {
violationRules {
rule {
limit {
minimum = 0.7
}
failOnViolation true
}
}
}
jacoco {
toolVersion = "0.8.1"
}
// to run coverage verification during the build (and fail when appropriate)
check.dependsOn jacocoTestCoverageVerification
当我使用上面的
./gradlew clean build
运行 build.gradle
时(^^^),如果我的覆盖率低于 70%,Jacoco 会 导致构建失败。 但是它不会为我生成任何 HTML 报告,这对于修复它没有任何帮助。
有什么想法吗?
请注意,Gradle Jacoco 插件确实提供了两个完全不相关的功能:
JacocoReport
)JacocoCoverageVerification
)如果该插件与 Java Plugin 一起应用,则会创建上述每种类型的任务,即
jacocoTestReport
和 jacocoTestCoverageVerification
。正如您从名称中看到的,它们都与 test
任务相关联。
但是,这些任务都不会自动包含到常规 Gradle
build
生命周期中。不包括报告任务的原因很简单,因为它对于实际构建实际的软件来说不是必需的。出于同样的原因,javadoc
任务不包含在build
生命周期中(可能是在创建 javadoc jar 时)。不包含验证任务的原因比较棘手,但我们简单引用一下文档:
任务不是Java插件提供的JacocoCoverageVerification
任务的任务依赖项。这是有充分理由的。该任务当前不是增量的,因为它没有声明任何输出。执行检查任务时,任何违反声明规则的行为都会自动导致构建失败。这种行为可能并不适合所有用户。 Gradle 的未来版本可能会改变行为。check
您已经通过将
check.dependsOn jacocoTestCoverageVerification
添加到构建文件中解决了这个问题。这样,每次构建都会检查代码覆盖率(如果不充分则失败)。现在您希望在所有构建中生成报告,即使由于代码覆盖率不足而失败。您需要确保在构建可能失败之前生成报告。你可以使用:
jacocoTestCoverageVerification.dependsOn jacocoTestReport
默认情况下启用 HTML 报告。所以没有必要在配置中放入html.enabled
。此外,文档还显示了如何指定目标文件夹。您可以尝试将其设置到某个已知文件夹以检查它是否有效,例如
html.destination file("${buildDir}/jacocoHtml")
。 HTML 报告的默认报告目录是 $buildDir/reports/jacoco/test
将 Jacoco 报告目录设置为某个明确的值也可以帮助识别任何配置问题reportsDir
。jacocoTestReport {
reports {
xml.required = true
csv.required = true
html.required = true
}
}