SpringMVC/ mockMVC/ jsonpath compare list of strings

前端 未结 2 1865
予麋鹿
予麋鹿 2020-12-24 13:42

I am currently writing some unit tests for a Spring MVC project. As the returned media type is JSON, I try to use jsonPath to check if the correct values are returned.

相关标签:
2条回答
  • 2020-12-24 14:19

    Here is what I ended up using:

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

    and

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

    0 讨论(0)
  • 2020-12-24 14:24

    1) Instead of

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

    try

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

    or

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

    2) Instead of

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

    try

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

    Keep in mind that you have to add hamcrest-library.

    0 讨论(0)
提交回复
热议问题