SpringMVC / mockMVC / jsonpath比较字符串列表 [英] SpringMVC/ mockMVC/ jsonpath compare list of strings

查看:1039
本文介绍了SpringMVC / mockMVC / jsonpath比较字符串列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

The trouble I have is to verify if a list of strings contains the correct (and only the correct) values.

我的计划是:


  1. 检查列表是否具有正确的长度

  2. 对于应该返回的每个元素,检查它是否在列表中

遗憾的是,这些似乎都不起作用。

sadly, none of these things seem to work.

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

Here's the relevant part of my code:

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

Only the first two "expectations" (isOk & isArray) are working. The other ones (for length and content) I can twist and turn however I want, they're not giving me any useful result.

有什么建议吗?

推荐答案

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。

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

这篇关于SpringMVC / mockMVC / jsonpath比较字符串列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆