我有一个Spring项目,其中写了一些单元测试和集成测试。现在,我想创建用于运行所有单元测试,所有集成测试和一项用于运行两者的自定义任务。但是我该怎么办?
答案 0 :(得分:0)
我建议将集成测试分成单独的源集。默认情况下,您已经有2个源集,一个用于生产代码,一个用于测试。要创建新的源集(在src/integrationTest/java
下创建新目录)并使用Junit5添加以下配置:
test {
useJUnitPlatform()
}
sourceSets {
integrationTest {
java.srcDir file("src/integrationTest/java")
resources.srcDir file("src/integrationTest/resources")
compileClasspath += sourceSets.main.output + configurations.testRuntime
runtimeClasspath += output + compileClasspath
}
}
对于单独的任务:
task integrationTest(type: Test) {
description = 'Runs the integration tests.'
group = 'verification'
testClassesDirs = sourceSets.integrationTest.output.classesDirs
classpath = sourceSets.integrationTest.runtimeClasspath
useJUnitPlatform()
reports {
html.enabled true
junitXml.enabled = true
}
}
现在您可以执行3个任务:
gradlew test
gradlew integrationTest
gradlew check
-同时运行,因为这都取决于同时扩展的测试任务如果您还使用jacoco并希望合并测试结果,则可以执行以下任务:
task coverageMerge(type: JacocoMerge) {
destinationFile file("${rootProject.buildDir}/jacoco/test.exec")
executionData fileTree(project.rootDir.absolutePath).include("**/build/jacoco/*.exec")
}
// aggregate all coverage data at root level
if (tasks.findByName("test")) {
tasks.findByName("test").finalizedBy coverageMerge
}
if (tasks.findByName("integrationTest")) {
tasks.findByName("integrationTest").finalizedBy coverageMerge
}
task codeCoverageReport(type: JacocoReport) {
executionData fileTree(project.rootDir.absolutePath).include("**/build/jacoco/*.exec")
subprojects.each {
if (!it.name.contains('generated')) {
sourceSets it.sourceSets.main
}
}
reports {
xml.enabled true
html.enabled true
html.setDestination(new File("${buildDir}/reports/jacoco"))
csv.enabled false
}
}
要运行覆盖率报告,只需执行
gradlew codeCoverageReport