【问题标题】:How to test Spring MVC controller with pagination?如何使用分页测试 Spring MVC 控制器?
【发布时间】:2017-12-05 16:54:00
【问题描述】:

我在为使用 ThymeleafSpring boot 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)

我有护目镜,但在这里没有运气。谁能帮我举个例子来测试一个处理存储库中的可分页对象的控制器吗?

有没有其他方法可以用分页测试列表?请帮忙。

提前致谢!

【问题讨论】:

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


    【解决方案1】:

    您正在测试属性contentscontentsPage 类型,因为您以该名称将其添加到模型中 (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

    【讨论】:

      【解决方案2】:

      模型中的“内容”不是集合类型,而是页面类型。所以你应该对 Page 类而不是 Collection 使用语义。从页面语义来看,它是 getTotalElements(),所以它是模型中的 pojo 字段 totalElements

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-07-16
        • 2014-05-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-24
        • 2013-08-11
        • 2021-04-01
        相关资源
        最近更新 更多