Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring mvc 如何使用分页测试Spring MVC控制器?_Spring Mvc_Junit_Mockito_Spring Mvc Test - Fatal编程技术网

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

Spring mvc 如何使用分页测试Spring MVC控制器?,spring-mvc,junit,mockito,spring-mvc-test,Spring Mvc,Junit,Mockito,Spring Mvc Test,我在为我的Spring boot MVCweb项目测试分页控制器时遇到了一个问题,该项目使用Thymeleaf。我的控制器如下: @RequestMapping(value = "admin/addList", method = RequestMethod.GET) public String druglist(Model model, Pageable pageable) { model.addAttribute("content", new ContentSearc

我在为我的Spring boot MVCweb项目测试分页控制器时遇到了一个问题,该项目使用Thymeleaf。我的控制器如下:

@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";

    }
但出现以下错误(分页前测试正常):

java.lang.AssertionError:模型属性“contents”
应为:大小为的集合
但是:是吗
位于org.hamcrest.matcherasert.assertThat(matcherasert.java:20)
我戴过眼镜,但在这里运气不好。有谁能帮我举个例子来测试一个控制器,它处理存储库中的可分页对象

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


提前谢谢

测试属性
内容
contents
的类型为
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实用程序类。通常我会像这里一样省略它们

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

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