我创建了使用gradle构建系统的Spring Boot项目。我想通过自定义渐变任务运行一个单独的测试类,以便在其他任务中依赖它。现在我可以用这个代码:
import org.apache.tools.ant.taskdefs.condition.Os
def gradleWrapper = Os.isFamily(Os.FAMILY_WINDOWS) ? 'gradlew.bat' : './gradlew'
task runMyTest(type: Exec) {
workingDir "$rootDir"
commandLine gradleWrapper, ':test', '--tests', 'com.example.MyTest'
}
显然,这不是一个非常漂亮的解决方案,因为它启动了一个额外的Gradle守护进程。我尝试过另一种解决方案:
task runMyTest(type: Test, dependsOn: testClasses) {
include 'com.example.MyTest'
}
但它不起作用(不要执行我的测试类(。
UPD:我尝试了另一种解决方案:
task runMyTest(type: Test) {
filter {
includeTestsMatching "com.example.MyTest"
}
}
它失败,并显示以下错误消息:
Execution failed for task ':runMyTest'.
> No tests found for given includes: [com.example.MyTest](filter.includeTestsMatching)
但是,很明显,我的测试是存在的,因为通过命令行运行测试会产生正确的结果。
UPD2:我在测试任务中错过了useJUnitPlatform()
。它在默认的测试任务中(由Spring Boot初始值设定项写入我的build.gradle(,但不在自定义任务中。
您可以使用TestFilter来完成此操作。
使用includeTestsMatching
可以指定您的类。
如果需要指定单个测试方法,可以使用includeTest "com.example.MyTest", "someTestMethod"
。
task runMyTest(type: Test) {
useJUnitPlatform()
filter {
includeTestsMatching "com.example.MyTest"
}
}