SpringMVC / MockMVC / jsonpath比较字符串列表


问题内容

我目前正在为Spring MVC项目编写一些单元测试。由于返回的媒体类型为JSON,因此我尝试使用jsonPath来检查是否返回了正确的值。

我遇到的麻烦是验证字符串列表是否包含正确的(并且只有正确的)值。

我的计划是:

  1. 检查清单长度是否正确
  2. 对于应该返回的每个元素,检查它是否在列表中

可悲的是,这些东西似乎都不起作用。

这是我的代码的相关部分:

Collection<AuthorityRole> correctRoles = magicDataSource.getRoles();

ResultActions actions = this.mockMvc.perform(get("/accounts/current/roles").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()) // works
.andExpect(jsonPath("$.data.roles").isArray()) // works
.andExpect(jsonPath("$.data.roles.length").value(correctRoles.size())); // doesn't work

for (AuthorityRole role : correctRoles) // doesn't work
  actions.andExpect(jsonPath("$.data.roles[?(@=='%s')]", role.toString()).exists());

仅前两个“期望”(isOk和isArray)有效。我可以随意旋转(在长度和内容上)的其他参数,它们没有给我任何有用的结果。

有什么建议么?


问题答案:

1)代替

.andExpect(jsonPath("$.data.roles.length").value(correctRoles.size()));

尝试

.andExpect(jsonPath("$.data.roles.length()").value(correctRoles.size()));

要么

.andExpect((jsonPath("$.data.roles", Matchers.hasSize(size))));

2)代替

for (AuthorityRole role : correctRoles) // doesn't work
  actions.andExpect(jsonPath("$.data.roles[?(@=='%s')]", role.toString()).exists());

尝试

actions.andExpect((jsonPath("$.data.roles", Matchers.containsInAnyOrder("role1", "role2", "role3"))));

请记住,您必须添加hamcrest库。