这里是 Java 8 和 Gradle 4.6。我正在尝试配置我的 Gradle 构建以使用 Jacoco Plugin但我遇到了一些困难。我已经让它与 Checkstyle 和 Findbugs 一起工作,这样运行 ./gradlew clean build
就会调用 Checkstyle 和 Findbugs 任务,因为它们是 check
任务的依赖项。
我现在正在尝试让 Jacoco 工作:
- 它排除了我的
com.me.myapp.domain.model
包及其所有内容;和 - 如果非排除类的代码覆盖率低于 70%,我的构建将失败;和
- 通过或失败,我想要在
build/
目录下生成的 Jacoco 报告的 HTML 版本;和 - 理想情况下我可以使用相同的 Gradle 命令调用
./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
当我使用上面的 build.gradle
运行 ./gradlew clean build
时 (^^^) Jacoco 确实构建失败如果我的覆盖率不到 70%。 但是它不会为我生成任何 HTML 报告,这对修复它一点帮助都没有。
有什么想法吗?
最佳答案
请注意,Gradle Jacoco 插件确实提供了两个完全不相关的功能:
- 可以生成覆盖率报告(任务类型
JacocoReport
) - 它可以执行代码指标,例如让构建失败(任务类型
JacocoCoverageVerification
)
如果该插件与 Java 插件一起应用,则会创建上述每种类型的任务,即 jacocoTestReport
和 jacocoTestCoverageVerification
。正如您从名称中看到的那样,它们都与 test
任务相关联。
但是,这些任务都不会自动包含在常规 Gradle build
生命周期中。不包括报告任务的原因很简单,因为它不是实际构建实际软件所必需的。出于同样的原因,javadoc
任务不包含在 build
生命周期中(可能是在创建 javadoc jar 时)。不包括验证任务的原因比较棘手,但让我们简单地引用文档:
The
JacocoCoverageVerification
task is not a task dependency of thecheck
task provided by the Java plugin. There is a good reason for it. The task is currently not incremental as it doesn't declare any outputs. Any violation of the declared rules would automatically result in a failed build when executing the check task. This behavior might not be desirable for all users. Future versions of Gradle might change the behavior.
您已经通过将 check.dependsOn jacocoTestCoverageVerification
添加到您的构建文件中解决了这个问题。这样,每次构建都会检查代码覆盖率(如果不足够则失败)。现在您想要在所有构建中生成报告,即使它由于代码覆盖率不足而失败。您需要确保在构建可能失败之前生成报告。你可以使用:
jacocoTestCoverageVerification.dependsOn jacocoTestReport
关于java - Gradle Jacoco 插件不生成报告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51267421/