如何在Karate中校验所有响应对象的type字段为fiction或non-fiction
正确的校验实现方式
你的原代码问题在于 match response contains schema 只会检查响应数组中至少存在一个符合规则的对象,但你需要的是所有对象的type字段值都只能是fiction或non-fiction,所以得调整写法,以下是两种可行的实现方式:
方法一:用match each逐个校验数组元素
* def allowedTypes = ['fiction', 'non-fiction'] * match each response == { type: '#? allowedTypes.contains(_)' }
match each会遍历响应数组的每一个元素,强制要求每个对象的type字段值都在allowedTypes列表内。
方法二:定义数组Schema匹配整个响应
* def allowedTypes = ['fiction', 'non-fiction'] * def bookSchema = { type: '#? allowedTypes.contains(_)' } * def responseSchema = '#[] bookSchema' * match response == responseSchema
这里#[] bookSchema表示一个数组结构,其中每个元素都必须符合bookSchema的校验规则,这样就能确保整个响应数组里的所有对象都满足type字段的限制。
扩展:全面校验对象结构
如果需要同时校验其他字段的类型或存在性,可以扩展Schema:
* def allowedTypes = ['fiction', 'non-fiction'] * def bookSchema = { id: '#number', name: '#string', type: '#? allowedTypes.contains(_)', available: '#boolean' } * match each response == bookSchema
这样不仅校验type的取值范围,还能确保id是数字、name是字符串、available是布尔值。
内容的提问来源于stack exchange,提问作者roudlek
相关产品推荐
相关产品推荐

