You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Gradle项目中Spock Framework Where测试用例为何未单独命名?

解决Spock Framework中Where子句测试用例未拆分显示的问题

核心原因与关键修复

Spock默认不会自动拆分Where子句的参数化测试用例,必须通过@Unroll注解显式开启拆分,同时配合Gradle/IntelliJ的配置来显示每个用例的详细信息。

1. 给测试方法添加@Unroll注解

修改测试代码,添加@Unroll并优化方法名称,让每个参数化用例的名称包含参数值:

import spock.lang.Unroll

class ArtifactoryManagerTest extends Specification {
    final static String artifact = 'artifact'
    final static String version = '1.2.3'

    @Unroll
    def "getLayoutSpecificPathHappyPath: platform #platform returns #expected"() {
        given:
        when:
        def result = artifactoryManager.getLayoutSpecificPath(platform, artifact, version)

        then:
        result == expected

        where:
        platform | expected
        'npm'    | "${artifact}/-"
        'maven'  | "${artifact}/${version}"
    }
}

注:原代码中Where子句的prefix列未在测试中使用,建议移除避免冗余。

2. 配置Gradle测试任务

在build.gradle(或build.gradle.kts)中添加测试日志配置,确保命令行运行时能看到每个用例的结果:

test {
    useJUnitPlatform() // 确保兼容Spock 2.x+

    testLogging {
        events 'PASSED', 'FAILED', 'SKIPPED'
        showExceptions = true
        showCauses = true
        showStackTraces = true
        displayGranularity = 2 // 显示到单个测试用例级别
        exceptionFormat = 'full'
    }
}

执行./gradlew test后,失败的用例会显示具体参数,比如:ArtifactoryManagerTest > getLayoutSpecificPathHappyPath: platform npm returns artifact/- FAILED

3. 调整IntelliJ运行设置

  • 打开Settings → Build, Execution, Deployment → Build Tools → Gradle → Runner,勾选Delegate IDE build/run actions to Gradle,让IntelliJ使用Gradle的配置运行测试
  • 在测试的Run/Debug Configuration中,进入Configuration标签页,在Test logging区域勾选Show passed tests和Show failed tests,并将Log level设为INFO

内容的提问来源于stack exchange,提问作者Peter Kahn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 18:46:14