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

如何使用RestAssured对JSON二维数组进行断言校验

问题根因

你遇到的报错本质是Matcher类型不匹配:arrayContainingInAnyOrder 是Hamcrest提供的专门匹配原生数组的匹配器,而RestAssured的JsonPath默认将JSON数组解析为List类型,哪怕内容完全一致,类型不匹配也会导致断言失败。

解决方案

方案1:替换为适配List的匹配器(最推荐)

直接把arrayContainingInAnyOrder替换为Hamcrest中适配Iterable/List的containsInAnyOrder匹配器即可,不需要修改其他逻辑:

// 仅修改对应断言行即可
.body("data.data[0]", containsInAnyOrder("elementZero", "elementOne", "elementTwo"))

注意提前导入对应的包:

import static org.hamcrest.Matchers.containsInAnyOrder;

方案2:手动转成数组后断言

如果你需要坚持使用arrayContainingInAnyOrder,可以先提取对应字段转成字符串数组再做断言:

// 先提取响应其他字段的断言不变
Response response = given()
        .auth().oauth2(token)
        .when()
        .pathParam("orderId", orderId)
        .get("/getScreeningsForOrder/{orderId}")
        .then()
        .statusCode(200)
        .contentType(ContentType.JSON)
        .body("status.code", equalTo("00"))
        .body("status.message", equalTo("SUCCESS"))
        .body("status.timestamp", Matchers.startsWith(expectedTimestamp_yyyyMMdd))
        .extract()
        .response();

// 提取目标数组转成String数组后单独断言
List<String> actualList = response.jsonPath().getList("data.data[0]");
String[] actualArray = actualList.toArray(new String[0]);
assertThat(actualArray, arrayContainingInAnyOrder("elementZero", "elementOne", "elementTwo"));

方案3:嵌套匹配器校验整个二维数组

如果你需要校验整个data.data二维数组的结构和内容,可以直接用嵌套匹配器:

.body("data.data", containsInAnyOrder(containsInAnyOrder("elementZero", "elementOne", "elementTwo")))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 01:06:08