如何用分页测试Spring MVC控制器?

时间:2017-07-02 07:10:57

标签: spring-mvc junit mockito spring-mvc-test

我在使用 Thymeleaf Spring启动MVC Web项目测试控制器时遇到了问题。我的控制器如下:

@RequestMapping(value = "admin/addList", method = RequestMethod.GET)
    public String druglist(Model model, Pageable pageable) {

        model.addAttribute("content", new ContentSearchForm());
        Page<Content> results = contentRepository.findContentByContentTypeOrByHeaderOrderByInsertDateDesc(
                ContentType.Advertisement.name(), null, pageable);


        PageWrapper<Content> page = new PageWrapper<Content>(results, "/admin/addList");
        model.addAttribute("contents", results);
        model.addAttribute("page", page);
        return "contents/addcontents";

    }

我已尝试使用以下测试段来计算内容项(最初它将返回带有分页的0项)。

andExpect(view().name("contents/addcontents"))
    .andExpect(model().attributeExists("contents"))
    .andExpect(model().attribute("contents", hasSize(0)));

但是得到以下错误(测试很好,在分页之前):

 java.lang.AssertionError: Model attribute 'contents'
Expected: a collection with size <0>
     but: was <Page 0 of 0 containing UNKNOWN instances>
 at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)

我已经护目镜但在这里没有运气。任何人都可以帮我一个例子来测试一个控制器来处理来自存储库的可分页对象吗?

是否存在使用分页测试列表的替代方法?请帮忙。

提前致谢!

2 个答案:

答案 0 :(得分:2)

您正在测试属性contentscontents类型为Page,因为您将该名称添加到模型中(model.addAttribute("contents", results);Page没有属性大小,它不是列表。

您想要检查元素总数:

.andExpect(view().name("contents/addcontents"))
.andExpect(model().attributeExists("contents"))
.andExpect(model().attribute("contents", Matchers.hasProperty("totalElements", equalTo(0L))));

为了您的方便,我已经包含了Hamcrest实用程序类。通常我会像https://github.com/EuregJUG-Maas-Rhine/site/blob/ea5fb0ca6e6bc9b8162d5e83a07e32d6fc39d793/src/test/java/eu/euregjug/site/web/IndexControllerTest.java#L172-L191

一样省略它们

答案 1 :(得分:2)

您的内容&#34;在模型中,它不是集合类型,它是页面类型。所以你应该为Page class使用语义而不是Collection。从页面语义到它的getTotalElements()所以它在模型中的pojo字段totalElements

andExpect(model().attribute("contents", Matchers.hasProperty("totalElements", equalTo(0L))));