首页 > 解决方案 > 如何在 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 中获取一些值

标签: javaspringjunithamcrest

解决方案


为了检查 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 的所有可能方法的完整列表可以在这里找到


推荐阅读