如何为下述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
相关产品推荐
相关产品推荐

