使用 spring Restdocs 以随机顺序匹配数组中的 json 值

问题描述 投票:0回答:1

我正在使用 Spring RestDocs 来验证我的 REST API。

一个 API 返回基于某些输入的生成值的数组。我想验证响应中生成的值是否正确。

回应可能是:

{ "hybrids": ["horsephant", "pussydog", "tigerbird"]

由于值的顺序不相关,下次调用 API 可能会导致:

{ "hybrids": ["pussydog", "horsedonkey", "tigerbird"]

我在 RestDoc 测试中使用以下代码片段:

.jsonPath("$.hybrids[0]").isEqualTo("pussydog")             .jsonPath("$.hybrids[1]").isEqualTo("horsedonkey")              .jsonPath("$.hybrids[2]").isEqualTo("tigerbird");

只有当订单不小心出现这样的情况时,才会通过。如何删除项目的顺序并使两个响应都导致测试通过?

谢谢

json spring rest jsonpath spring-restdocs
1个回答
0
投票

答案在于在 jsonPath 检查中使用 Hamcrest 匹配器:

.jsonPath("$.hybrids[*]", CoreMatchers.hasItem("pussydog"))
.jsonPath("$.hybrids[*]", CoreMatchers.not(CoreMatchers.hasItem("banana"))

等等(可能想要静态导入 CoreMatchers.*,但这取决于你)

© www.soinside.com 2019 - 2024. All rights reserved.