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

时间:2013-03-12 20:03:32

标签: java spring-mvc jsonpath

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

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

我的计划是:

  1. 检查列表的长度是否正确
  2. 对于应该返回的每个元素,检查它是否在列表中
  3. 遗憾的是,这些事情似乎都不起作用。

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

    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&amp; isArray)才有效。其他的(长度和内容)我可以扭曲和转动但是我想要的,他们没有给我任何有用的结果。

    有什么建议吗?

2 个答案:

答案 0 :(得分:54)

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-library。

答案 1 :(得分:3)

以下是我最终使用的内容:

.andExpect(jsonPath('$.data.roles').value(Matchers.hasSize(size)))

.andExpect(jsonPath('$.data.roles').value(Matchers.containsInAnyOrder("role1", "role2", "role3")))

相关问题