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

如何为下述Groovy代码编写shouldFail与ShouldPass测试用例?

Groovy代码withLocal的测试用例(成功/失败场景)

以下基于Spock框架编写测试用例,覆盖withLocal方法的成功与失败场景:

成功场景(ShouldPass)

当环境变量CREDENTIALS_ID设置有效值时,方法正常执行,无异常抛出,且输出对应凭证ID。

def "withLocal executes successfully when CREDENTIALS_ID is set"() {
    given:
    // 模拟环境变量存在有效值
    env.CREDENTIALS_ID = "prod-cred-456"
    def capturedEcho = []
    // 替换echo方法捕获输出内容
    def testTarget = new Expando(
        echo: { message -> capturedEcho.add(message) }
    )

    when:
    testTarget.withLocal {}

    then:
    // 验证输出内容匹配
    capturedEcho.first() == "credentials Id=prod-cred-456"
    // 确认无异常抛出
    noExceptionThrown()
}

失败场景(ShouldFail)

当环境变量CREDENTIALS_ID未设置或为空时,方法抛出指定异常。

def "withLocal throws exception when CREDENTIALS_ID is null"() {
    given:
    // 模拟环境变量未设置
    env.CREDENTIALS_ID = null
    def testTarget = new Expando(
        echo: { message -> }
    )

    when:
    testTarget.withLocal {}

    then:
    // 验证异常类型与信息
    Exception thrownException = thrown()
    thrownException.message == "credentials not setup - env.CREDENTIALS_ID"
}

def "withLocal throws exception when CREDENTIALS_ID is empty string"() {
    given:
    // 模拟环境变量为空字符串
    env.CREDENTIALS_ID = ""
    def testTarget = new Expando(
        echo: { message -> }
    )

    when:
    testTarget.withLocal {}

    then:
    Exception thrownException = thrown()
    thrownException.message == "credentials not setup - env.CREDENTIALS_ID"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 11:45:37