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

如何用Karate验证字段为指定对象Schema或空数组?

问题描述

我有一个用户列表,部分用户包含Organization信息,其余用户的organization字段为空数组。需要验证organization字段要么符合预设的schemaOrganization对象Schema,要么是空数组。

当前Karate代码

@performance
Feature: API Example Call

Background:
    * url url
    * def user = call read('../GetToken.feature') { accessToken : response.token }
    * def schemaOrganization = { id: '#string', name: '#string'}
    * def schemaUser = { id: '#string', name: '#string', organization: '#(schemaOrganization)'}


Scenario: Auth -> api/v1/users
Given path 'api/v1/users'
And header Authorization = 'Bearer '+ user.token
And header Accept-Language = 'en'
When method get
Then status 200
* def data = response.data
* match each data == schemaUser

已尝试的写法

  • organization: '##[] #(schemaOrganization)'
  • organization: '##[] schemaOrganization'
  • organization: '#[] #schemaOrganization'

待验证的响应数据

{
    "data":[
        {
            "id":"123-123-123",
            "name":"example-name",
            "organization":[
                
            ]
        },
        {
            "id":"234-234-234",
            "name":"example-test",
            "organization":{
                "id":"org-123",
                "name":"example-org"
            }
        }
    ]
}

解决方案

要实现“organization字段要么是符合schemaOrganization的对象,要么是空数组”的验证,修改schemaUser中的organization字段匹配规则,使用Karate的逻辑或(||)语法同时匹配两种情况即可:

* def schemaUser = { id: '#string', name: '#string', organization: '#(schemaOrganization) || ##[]'}

规则说明

  • #(schemaOrganization):匹配符合预设结构的Organization对象
  • ##[]:匹配空数组
  • ||:逻辑或运算符,字段满足任意一种格式即验证通过

修改后重新执行测试,就能正确验证两种格式的organization字段了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 22:03:17