Karate中如何实现允许awbDetails为Null或对象的Schema校验?
Karate Schema校验:允许字段为Null或指定对象的解决方案
问题场景
API返回的JSON响应如下:
[ { "capacityId": "c34ac5c9-0bdb-496b-a7e0-17bc76009f3f", "requestBreakdown": [ { "awbDetails": { "number": null, "date": "18042023", "weightInKg": 100, "awbStatus": "Pending", "bookingId": null } } ] }, { "capacityId": "6d75b2ae-3f51-49d9-8e85-a29c310143bd", "requestBreakdown": [ { "awbDetails": null } ] } ]
需要让awbDetails字段在校验时允许为null或符合指定结构的对象,尝试两种写法均报错:
- 写法1:
awbDetails: '#null #(awbDetailsSchema)'
报错:>>> failed features: java.util.LinkedHashMap cannot be cast to java.lang.String - 写法2:
awbDetails: '##(awbDetailsSchema)'
报错:>>> failed features: java.lang.NullPointerException
使用Karate版本为v1.3.0。
正确实现方式
方法1:使用#nullable()包裹子Schema
先定义awbDetails的结构Schema:
* def awbDetailsSchema = { number: '#nullable', date: '#string', weightInKg: '#number', awbStatus: '#string', bookingId: '#nullable' }
在父Schema中,通过#nullable()指定字段允许为null或符合子Schema的对象:
* def parentSchema = [ { capacityId: '#string', requestBreakdown: [ { awbDetails: '#nullable(awbDetailsSchema)' } ] } ]
方法2:直接组合#null与对象结构
如果不需要单独定义子Schema,可直接在字段中写组合规则:
* def parentSchema = [ { capacityId: '#string', requestBreakdown: [ { awbDetails: '#null || { number: #nullable, date: #string, weightInKg: #number, awbStatus: #string, bookingId: #nullable }' } ] } ]
错误原因说明
- 写法1错误:Karate不支持用空格直接拼接两个校验规则,这种写法会触发对象转字符串的类型转换异常。
- 写法2错误:
##用于标记可选字段(即字段可以不存在),但当前场景是字段存在但值为null,因此不适用,进而触发空指针异常。
内容的提问来源于stack exchange,提问作者pooventhan
相关产品推荐
相关产品推荐

