我目前正在为Spring MVC项目编写一些单元测试.由于返回的媒体类型是JSON,我尝试使用jsonPath检查是否返回了正确的值.
我遇到的麻烦是验证字符串列表是否包含正确的(并且只有正确的)值.
我的计划是:
可悲的是,这些东西似乎都没有用.
这是我的代码的相关部分:
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());
Run Code Online (Sandbox Code Playgroud)
只有前两个"期望"(isOk&isArray)才有效.其他的(长度和内容)我可以扭曲和转动但是我想要,他们没有给我任何有用的结果.
有什么建议?