You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Karate框架可选字段表达式匹配null值失败问题求助

解决Karate中customer字段可为null或对象的Schema匹配问题

问题场景

接口返回的customer字段要么是null,要么是包含有效字段的对象。按照Karate规则实现Schema匹配后,返回null的响应匹配失败。

匹配通过的响应(Response 1)

{
  "data": {
     "itemDescription": "chocolate",
     "itemAmount": 2.01,
     "customer":{
          "id": "1234",
          "firstName": "ABC",
          "lastName": "XYZ"
          },
     "oId": "764328421"
     }
}

匹配失败的响应(Response 2)

{
  "data": {
     "itemDescription": "chips",
     "itemAmount": 4.99,
     "customer": null,
     "oId": "8394821"
     }
}

测试代码

Feature: <>
Scenario Outline: <>
Given
When method POST
Then status 200
* match response == read('classpath:com/<schemapath>/JSONSchema.json')

当前错误的JSON Schema

{
  "data": {
     "itemDescription": "#string",
     "itemAmount": "#number",
     "customer":"##({id:'#string',firstName:'#string',lastName:'#string'})",
     "oId": "#string"
     }
}

注:原Schema存在语法错误(customer字段的字符串缺少闭合双引号),且##的用法不符合需求。

报错信息

$.data.customer | data types don't match (NULL:MAP)
null
{"id":"#string","firstName":"#string","lastName":"#string"}

解决方法

Karate中要实现字段支持null或指定结构对象的匹配,需调整Schema的写法:

方案1:使用#nullable(Karate 1.4+版本支持)

用#nullable包裹对象结构,直接声明字段可为null或指定对象:

{
  "data": {
     "itemDescription": "#string",
     "itemAmount": "#number",
     "customer": "#nullable({id:'#string', firstName:'#string', lastName:'#string'})",
     "oId": "#string"
     }
}

方案2:使用#or表达式兼容旧版本

若使用Karate 1.4之前的版本,可通过#or明确指定两种允许的情况:

{
  "data": {
     "itemDescription": "#string",
     "itemAmount": "#number",
     "customer": "#or null ({id:'#string', firstName:'#string', lastName:'#string'})",
     "oId": "#string"
     }
}

同时需修复原Schema中的语法错误,确保字符串引号闭合。

内容的提问来源于stack exchange,提问作者SKM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 02:33:30