java - 如何在 Java 中重写 ModelAndView 的集成测试
问题描述
我有那个控制器
@GetMapping("/popular")
public List<User> getPopularUsers() {
return handler.getPopularUsers();
}
并对其进行正确的集成测试:
mockMvc.perform(get("/popular"))
.andExpect(status().isOk())
.andExpect(jsonPath("[0].userId").value(372152))
.andExpect(jsonPath("[1].userId").value(398729));
现在我改变了我的控制器,它返回 ModelAndView 而不是 List:
@GetMapping("/popular")
public ModelAndView getPopularUsers(Map<String, Object> map) {
List<User> popularUsers = handler.getPopularUsers();
map.put("users", popularUsers);
return new ModelAndView("popular-users", map);
}
有人可以告诉我如何为新控制器重写测试吗?我找到了一些使用 hamcrest 库的示例,但我真的不明白如何从 List 中获取一些值
解决方案
为了检查 ModelAndView 案例,Spring MVC Test 有几个 MVC 匹配器,如 ModelResultMatchers 和 ViewResultMatchers
如果要检查列表中的某些值,可以使用public <T> ResultMatcher attribute(String name, Matcher<T> matcher)
ModelResultMatchers 中的方法。
以前的检查可以这样重写:
.andExpect(model().attribute("users",hasItem(hasProperty("id", equalTo(372152)))));
.andExpect(model().attribute("users",hasItem(hasProperty("id", equalTo(398729)))));
此外,您可以检查视图,这种情况的检查可能如下所示:
.andExpect(view().name("popular-users"))
所有 MockMvcResultMatchers 的完整列表可以在这里找到
可以在此处找到 ModelResultMatchers 的所有可能方法的完整列表
ViewResultMatchers 的所有可能方法的完整列表可以在这里找到
推荐阅读
- javascript - 每周五将活跃班级切换到下一个兄弟姐妹?Javascript / jQuery
- c - 为什么不可能有空数组?
- c# - 如何使用通用存储库模式获取所有子集合?
- javascript - 如何将空格字符串转换为数组
- php - 如何在 Laravel PHP 中将文件保存在服务器上
- java - Java 交换无效
- azure - Azure 自动化作业 OData $filter
- c# - 在 c# 的返回块中指定 if 条件时出现无法访问的代码错误
- android - 在 MVVM 架构中用 RxJava 替换 LiveData
- jenkins - Jenkins PER USER 默认参数值?