Karate如何实现JSON Schema条件校验:根据customerType动态校验字段
问题原因
你当前的Schema将person和organization都作为顶层固定字段声明,Karate默认会校验响应是否包含Schema中所有已声明的字段。当customerType为person时,响应没有organization字段,就会触发字段不匹配的报错。
解决方案
这里提供两种常用的实现方式,都可以满足两个字段互斥的校验要求:
方式一:单Schema加存在性校验
在原有条件判断的基础上,补充非对应类型下字段必须不存在的逻辑:
- 先定义两个子结构的校验规则:
// 个人信息子Schema def personSchema = { firstName: '#string', lastName: '#string' } // 机构信息子Schema def organizationSchema = { orgName: '#string', orgAddress: '#string' }
- 顶层校验Schema写法:
def customerSchema = { customerType: '#string', id: '#number', requestDate: '#string', // 类型为person时校验person结构,否则要求person字段不存在 person: '#? response.customerType == "person" ? karate.match(_, personSchema).pass : _ == undefined', // 类型为org时校验organization结构,否则要求organization字段不存在 organization: '#? response.customerType == "org" ? karate.match(_, organizationSchema).pass : _ == undefined' }
方式二:分场景Schema加逻辑或判断
把两种互斥的响应结构拆分为独立Schema,再通过逻辑或校验匹配任意一种即可,可读性更高:
// 个人场景完整Schema def personCaseSchema = { customerType: '#(^"person")', person: '#(personSchema)', id: '#number', requestDate: '#string' } // 机构场景完整Schema def orgCaseSchema = { customerType: '#(^"org")', organization: '#(organizationSchema)', id: '#number', requestDate: '#string' } // 最终校验规则:匹配任意一种场景即可 def finalSchema = '#? karate.match(_, personCaseSchema).pass || karate.match(_, orgCaseSchema).pass'
校验调用
直接用最终的Schema和响应做匹配即可:
match response == finalSchema
内容的提问来源于stack exchange,提问作者stackoverflow
相关产品推荐
相关产品推荐

