Karate框架校验数组元素非空/非null时的匹配错误问题
问题分析
你遇到的报错是因为Karate的==匹配要求完全结构一致,你写的预期对象仅包含result[2].hostname这一个虚拟键,但实际的actualResponse是包含result数组的完整对象,数组内每个元素还有critical、minor等其他字段,因此会提示“实际值比预期多4个key”。
解决方案
根据你的需求,分两种场景给出正确写法:
场景1:检查数组中指定位置的元素(如索引2的第三个元素)的hostname不为空/非null
若仅需验证特定索引元素的hostname,同时忽略其他字段,使用contains匹配部分字段即可:
And match actualResponse.result[2] contains { hostname: '##notnull' }
也可以用##ignore明确忽略其他字段(写法更繁琐,适合需指定多个字段的场景):
And match actualResponse == { result: [ '##ignore', '##ignore', { hostname: '##notnull', critical: '##ignore', minor: '##ignore', syslog: '##ignore' } ] }
场景2:检查数组中是否存在任意一个元素的hostname为空或null
若要验证整个数组里是否有hostname为空字符串或null的元素,使用Karate的match some语法:
# 检查是否存在hostname为空字符串的元素 And match some actualResponse.result contains { hostname: '' } # 检查是否存在hostname为null的元素 And match some actualResponse.result contains { hostname: '#null' } # 同时检查是否存在空字符串或null的元素 And match some actualResponse.result contains { hostname: '#? _ == null || _ == ""' }
如果你的需求是确保数组中所有元素的hostname都不为空/非null(反向验证),则使用match each:
And match each actualResponse.result contains { hostname: '##notnull' } And match each actualResponse.result contains { hostname: '#? _ != ""' }
内容的提问来源于stack exchange,提问作者Cloudravi
相关产品推荐
相关产品推荐

