Karate框架下含数组的复杂响应Schema验证问题咨询
问题排查与修复方案
核心错误点
- 测试用例中将读取的Schema强制转换为字符串类型,导致匹配逻辑错误
read()方法读取JSON文件默认返回JSON对象,你通过string关键字强制将其转换为普通字符串,后续match response == jsonSchemaExpected变成了JSON对象和字符串的等值比对,必然匹配失败。 - 现有数组校验规则仅验证元素为对象,未覆盖内部字段校验(可选优化项)
当前"data": "#[] #object"仅能校验data是对象数组,不会校验数组内对象的字段类型,如需更严格的校验可以补充规则。
修复步骤
1. 修改Feature测试用例
删除Schema读取行的string类型强制转换,代码如下:
Scenario: Get all Users and validate schema Given url getUrl When method Get Then status 200 And print response Then match response == '#object' * def jsonSchemaExpected = read('file:src/test/resources/features/sample/responseSchema.json') And print response.data.length And match response == jsonSchemaExpected
2. (可选)完善responseSchema.json实现全字段校验
如果需要校验数组内每个对象的字段类型,修改Schema如下:
{ "page": "#number", "per_page": "#number", "total": "#number", "total_pages": "#number", "data": "#[] { id: #number, email: #string, first_name: #string, last_name: #string, avatar: #string }", "support": { "url": "#string", "text": "#string" } }
如果仅需要校验data是对象数组,无需修改原Schema文件,仅调整测试用例即可运行通过。
内容的提问来源于stack exchange,提问作者Rishabh anand
相关产品推荐
相关产品推荐

