我正在用spring编写一些集成测试,并想检查一下,来自response的json包含所有必需的数据。见代码:
@Test
public void getAll() throws Exception {
String url = "/permissions/all";
int size = 4;
try {
Set<String> permissions = RandomGenerator.randomStrings(size);
initDb(permissions);
mvc.perform(get(url).with(Users.PERMISSIONS_READ))
.andExpect(jsonPath("$[?(@.name)].name", hasSize(size))) //ok
.andExpect(jsonPath("$[?(@.name)].name").value(containsInAnyOrder(permissions))); //exception
} finally {
dropDb();
}
}
但我在这里得到一个例外:
java.lang.AssertionError: JSON path "$[?(@.name)].name"
Expected: iterable over [<[b0ce9e8a-8b62-41f4-91b9-d9cf6ff96675, 7ebe3a4f-7864-4ea5-92b3-a5ad6f44bf42, 7df2fa88-b22f-4d33-91b2-f8b00813522f, 17b61119-c48c-4dff-ac9c-047eb3efcc43]>] in any order
but: Not matched: "7df2fa88-b22f-4d33-91b2-f8b00813522f"
来自此回复的数据:
[{
"id": 1,
"name": "7df2fa88-b22f-4d33-91b2-f8b00813522f"
}, {
"id": 2,
"name": "b0ce9e8a-8b62-41f4-91b9-d9cf6ff96675"
}, {
"id": 3,
"name": "7ebe3a4f-7864-4ea5-92b3-a5ad6f44bf42"
}, {
"id": 4,
"name": "17b61119-c48c-4dff-ac9c-047eb3efcc43"
}]
我知道,选择器$[?(@.name)].name
工作正常,并返回以下结果:
[
"7df2fa88-b22f-4d33-91b2-f8b00813522f",
"b0ce9e8a-8b62-41f4-91b9-d9cf6ff96675",
"7ebe3a4f-7864-4ea5-92b3-a5ad6f44bf42",
"17b61119-c48c-4dff-ac9c-047eb3efcc43"
]
permissions
设置也正确,包含4个字符串,如上例所示。
有人可以告诉我,我在这里做错了吗?
答案 0 :(得分:3)
这将有效:
Set<String> permissions = RandomGenerator.randomStrings(size);
initDb(permissions);
mvc.perform(get(url).with(Users.PERMISSIONS_READ))
.andExpect(jsonPath("$[?(@.name)].name", hasSize(size))) //ok
.andExpect(jsonPath("$[?(@.name)].name").value(containsInAnyOrder(permissions.toArray(new String[permissions.size()]))));
或重申:
String[] permissions = RandomGenerator.randomStrings(size);
initDb(permissions);
mvc.perform(get(url).with(Users.PERMISSIONS_READ))
.andExpect(jsonPath("$[?(@.name)].name", hasSize(size))) //ok
.andExpect(jsonPath("$[?(@.name)].name").value(containsInAnyOrder(permissions)));
这里是containsInAnyOrder
的签名:
public static <T> Matcher<Iterable<? extends T>> containsInAnyOrder(T... items)
因此,它期望您声明的相同类型的变量。在您的情况下,您正在针对类型String
进行断言,但是您正在向Set<String>
提供containsInAnyOrder
,因此String和Set之间的匹配失败。