Kotest标签筛选命令失效及MacOS下语法报错问题求助
问题描述
我使用的Kotest依赖版本如下:
testImplementation(platform("io.kotest:kotest-bom:5.8.0")) testImplementation("io.kotest.extensions:kotest-extensions-spring:1.1.3") testImplementation("io.kotest:kotest-assertions-core") testImplementation("io.kotest:kotest-assertions-json-jvm") testImplementation("io.kotest:kotest-runner-junit5-jvm") testImplementation("io.kotest:kotest-framework-datatest") testImplementation("io.kotest:kotest-property")
自定义了标签BEAVER,测试类代码如下:
object BEAVER: Tag() class TagPlaygroundTest: StringSpec({ tags(BEAVER) "should pass with tag".config(tags = setOf(BEAVER)) { 3 shouldBe 3 } "should fail with tag".config(tags = setOf(BEAVER)) { 3 shouldBe 4 } })
遇到两个问题:
- 执行命令
./gradlew test -Dkotest.tags="BEAVER"时,所有测试(包括无标签的)都会被执行; - 在MacOS的zsh环境下执行
./gradle test -Dkotest.tags="Linux & !Database"会报错zsh: event not found: Database。
需求是通过gradlew或自定义Gradle任务仅运行带有指定标签的测试。
解决办法
1. 仅运行指定标签的测试(排除无标签测试)
Kotest默认会执行匹配标签的测试,但不会自动排除无标签的测试,需要通过参数或配置明确过滤:
方式一:命令行指定标签模式
执行命令时添加kotest.tag.mode=include参数,明确仅包含匹配标签的测试:
./gradlew test -Dkotest.tags="BEAVER" -Dkotest.tag.mode=include
方式二:自定义Gradle任务
在build.gradle.kts中添加专属任务,避免每次命令行输入参数:
tasks.register<Test>("testBeaver") { useJUnitPlatform() systemProperty("kotest.tags", "BEAVER") systemProperty("kotest.tag.mode", "include") }
执行时直接运行:
./gradlew testBeaver
2. 解决zsh环境下&符号报错问题
zsh会将&解析为后台执行命令,需要通过以下方式规避:
方式一:用单引号包裹标签表达式
./gradlew test -Dkotest.tags='Linux & !Database' -Dkotest.tag.mode=include
方式二:转义&符号
./gradlew test -Dkotest.tags="Linux \& !Database" -Dkotest.tag.mode=include
方式三:通过Gradle任务配置
同样可以把复杂的标签表达式写到自定义任务里,避免命令行转义:
tasks.register<Test>("testLinuxExcludeDatabase") { useJUnitPlatform() systemProperty("kotest.tags", "Linux & !Database") systemProperty("kotest.tag.mode", "include") }
执行:
./gradlew testLinuxExcludeDatabase
内容的提问来源于stack exchange,提问作者Damian Tański
相关产品推荐
相关产品推荐

