You need to enable JavaScript to run this app. Rest-Assured与Hamcrest匹配器对比int数组时失效问题排查
优惠活动
大模型
产品
解决方案
定价
更多

Rest-Assured与Hamcrest匹配器对比int数组时失效问题排查

问题描述

REST响应体:

{"error": {"errorObjects": [{"risks": [{"description": "Risk1","riskId": 6654152},{"description": "Risk2","riskId": 6654155}]}]}}

定义的预期数据数组:

int[] riskId = {6654152, 6654155}
String[] description =  {"Risk1",  "Risk2"}

使用Rest Assured和Hamcrest Matchers编写的断言代码:

.body("error.errorObjects[0].risks.description", containsInRelativeOrder(description), "error.errorObjects[0].risks.riskId",containsInRelativeOrder(riskId));

执行后报错:

java.lang.AssertionError: 1 expectation failed.
JSON path error.errorObjects[0].risks.riskId doesn't match.
Expected: ((a collection containing [<6654152>, <6654155>]))
  Actual: <[6654152, 6654155]>

字符串数组对比正常,但int数组对比失败,尝试多个匹配器仍无法解决,需更换匹配器或其他解决办法?

解决办法
  • 核心原因:Hamcrest的containsInRelativeOrder对基本类型数组(如int[])适配性差,JSON解析后返回的riskId是Integer类型集合,与传入的int[]类型不匹配,导致断言失败。

  • 方案1:替换为包装类数组
    将预期的int[]改为Integer[],直接使用原有断言逻辑:

Integer[] riskId = {6654152, 6654155};
.body("error.errorObjects[0].risks.description", containsInRelativeOrder(description), "error.errorObjects[0].risks.riskId", containsInRelativeOrder(riskId));
  • 方案2:转换为集合后断言
    把int数组转为集合,结合集合匹配器使用:
import java.util.Arrays;
// ...
.body("error.errorObjects[0].risks.riskId", containsInRelativeOrder(Arrays.asList(6654152, 6654155)));
  • 方案3:改用equalTo匹配器(无需校验顺序)
    若只需验证元素一致、不关心顺序,直接用equalTo即可,Rest Assured会自动兼容基本类型数组:
.body("error.errorObjects[0].risks.riskId", equalTo(riskId));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 01:55:11