Karate框架复杂JSON Schema匹配:响应体验证Schema是否可行?
在Karate框架中进行复杂JSON Schema匹配的可行性分析
问题概述
在Karate框架中验证如下JSON响应体时,用户编写的Schema匹配逻辑是否可行?
示例JSON
{"id": 5,"category": {"id": 0,"name": "string"},"name": "doggie","photoUrls": ["string"],"tags": [{"id": 0,"name": "string"}],"status": "string"}
用户编写的场景代码
* def json = """ {"id": 5,"category": {"id": 0,"name": "string"},"name": "doggie","photoUrls": ["string"],"tags": [{"id": 0,"name": "string"}],"status": "string"} """ * def tags = { id: '#integer', name: '#string'} * def photoUrls = { string: '#string' } * def category = { id: '#integer',name: '#string'} * def MYinternalDetails = """ { id: '#string', name: '#string' status: '#string' textfield: '##[] textfield', tags: '##[] tags', photoUrls: '##[] photoUrls', category: '##{} category', } """ * match json == '#[] MYinternalDetails'
问题分析与修正
原代码存在多处错误,无法完成正确匹配,具体问题及修正方案如下:
- 语法错误:
MYinternalDetails中name和status字段后缺少逗号,JSON格式不合法,会直接导致Karate执行报错。 - 类型不匹配:示例JSON中
id是整数类型,但Schema里定义为#string,匹配时会失败,应改为#integer。 - 多余字段:Schema中新增了
textfield字段,但示例JSON中不存在该字段,Karate默认严格匹配会失败,需移除该字段。 - 数组定义错误:
photoUrls是字符串数组,原定义{ string: '#string' }完全错误,无需单独定义对象,直接在Schema中用'#[] #string'即可;若要复用逻辑,可定义photoUrlItem = '#string',再用'##[] photoUrlItem'。 - 匹配目标错误:示例JSON是单个对象,不是数组,最后一行的
#[] MYinternalDetails错误,应改为#{} MYinternalDetails或者直接使用MYinternalDetails。
修正后的代码
* def json = """ {"id": 5,"category": {"id": 0,"name": "string"},"name": "doggie","photoUrls": ["string"],"tags": [{"id": 0,"name": "string"}],"status": "string"} """ * def tags = { id: '#integer', name: '#string'} * def category = { id: '#integer', name: '#string'} * def MYinternalDetails = """ { id: '#integer', name: '#string', status: '#string', tags: '##[] tags', photoUrls: '#[] #string', category: '##{} category' } """ * match json == MYinternalDetails
若要复用photoUrls的校验逻辑,可调整为:
* def photoUrlItem = '#string' * def MYinternalDetails = """ { id: '#integer', name: '#string', status: '#string', tags: '##[] tags', photoUrls: '##[] photoUrlItem', category: '##{} category' } """
内容的提问来源于stack exchange,提问作者Arturo Llempen
相关产品推荐
相关产品推荐

