Karate API响应校验:验证错误数组中含指定前缀的reason字段
问题描述
我有如下API响应:
{ errors: [ { code: 123, reason: "this is the cause for a random problem where the last part of this string is dynamically generated" }, { code: 234, reason: "Some other error for another random reason" } ... ] }
我用以下语句校验响应:
... And match response.errors[*].reason contains "this is the cause"
但校验失败,因为该语句会对每个reason做完整字符串相等性检查。我的实际需求是:校验errors数组中是否存在某个error对象,其reason属性的值以“this is the cause”开头。试了通配符没用,该怎么实现?
解决方案
可以通过正则匹配或者调用字符串的startsWith方法实现需求,以下是两种常用写法:
方式1:正则匹配
使用matches关键字配合正则表达式^this is the cause.*(^锚定字符串开头,.*匹配后续任意字符),同时结合some关键字指定“数组中至少存在一个元素满足条件”:
And match response.errors contains some { reason matches '^this is the cause.*' }
方式2:调用字符串方法
如果测试框架支持直接调用字符串原生方法,也可以用startsWith来判断:
And match response.errors contains some { reason.startsWith('this is the cause') }
这两种写法都会精准检查errors数组中是否存在目标error对象,既不会要求所有元素满足条件,也不会做完整字符串的相等校验。
内容的提问来源于stack exchange,提问作者ThrowableException
相关产品推荐
相关产品推荐

