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

标签 java spring-mvc 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-library。

关于java - SpringMVC/mockMVC/jsonpath 比较字符串列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15371022/

相关文章:

java - 无法在 bluemix 上使用 java 注释初始化数据源

基于 Java 的 JSON 操作

没有单例的 Java

Java错误api级别的方法

java - Spring 启动 2 : Get html output in controller

java - Spring OAuth2 client_credentials 与预身份验证用户相结合

spring-mvc - Spring MVC中的有序RequestMapping

java - 如何通过 Jayway JsonPath 将带有嵌套列表的 json 展平?

java - 如何使用 JsonPath 向 Json 添加新节点?

java - Hibernate - 使用@OneToMany 或@ManyToMany 定位未映射的类 : com. podro.model.Journey.roadWay[com.podro.model.RoadElement]