Groovy脚本断言失效:测试步骤属性值不匹配却未触发断言
问题
我编写了如下Groovy脚本,用于对比TestCase中TestStep_1与TestStep_2的指定属性值,通过map关联两者的属性对应关系:
def map = ['Response' : 'id'] def p1 = context.testCase.testSteps["TestStep_1"].properties def p2 = context.testCase.testSteps["TestStep_2"].properties def result = [] def assertPropertyValue = { p1key, p2key -> def temp = p1[p1key].value == p2[p2key].value log.info("Comparing $p1key, and $p2key values respectively ${p1[p1key].value} == ${p2[p2key].value} ? $temp") temp } map.each { result << assertPropertyValue(it.key, it.value) } assert result.each{it.value == true}, 'Comparison failed, check log'
但当TestStep_2的id值与TestStep_1的Response属性中的id不匹配时,日志显示对比结果为false:
Fri Aug 12 17:48:16 CEST 2022:INFO:Comparing Response, and id values respectively {"code":"200","timestamp":"Fri Aug 12 15:12:45 UTC 2022","HttpStatus":"OK","id":"8154b2d1-4f83-4b2c-b100-5dab36b37ab6"} == 929c2a62-5c8a-4e85-bf65-776696503818 ? false
此时脚本并未触发预设的断言提示“Comparison failed, check log”,请问这是什么原因?
原因分析与解决办法
核心原因:each方法的返回值特性导致断言失效
Groovy中的each方法始终返回调用它的原始集合对象,而非遍历逻辑的执行结果。你写的result.each{it.value == true}不管遍历过程中每个元素的判断结果如何,最终返回的都是result集合本身。
在Groovy的布尔判断规则里,非空集合会被判定为true,所以assert的条件永远成立,自然不会触发错误提示。
修正步骤
替换断言逻辑:用
every方法替代each,every会遍历集合并验证所有元素是否满足条件,最终返回布尔值:// 两种等价写法 assert result.every{ it == true }, 'Comparison failed, check log' // 更简洁的写法,因为集合元素本身就是布尔值 assert result.every(), 'Comparison failed, check log'修复值对比的逻辑错误:从日志能看到,TestStep_1的Response是完整的JSON字符串,而TestStep_2的id是单独的UUID值,直接用
==对比肯定不相等。需要先解析JSON提取id字段再对比:import groovy.json.JsonSlurper def map = ['Response' : 'id'] def p1 = context.testCase.testSteps["TestStep_1"].properties def p2 = context.testCase.testSteps["TestStep_2"].properties def result = [] def jsonSlurper = new JsonSlurper() def assertPropertyValue = { p1key, p2key -> // 解析Response的JSON字符串,提取其中的id字段 def p1Value = jsonSlurper.parseText(p1[p1key].value).id def p2Value = p2[p2key].value def temp = p1Value == p2Value log.info("Comparing $p1key's id, and $p2key values respectively ${p1Value} == ${p2Value} ? $temp") temp } map.each { result << assertPropertyValue(it.key, it.value) } assert result.every(), 'Comparison failed, check log'
内容的提问来源于stack exchange,提问作者gibb
相关产品推荐
相关产品推荐

