我在测试使用 Thymeleaf 的 Spring boot MVC Web 项目的分页 Controller 时遇到问题。我的 Controller 如下:
@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)
我已经护目镜了,但这里运气不佳。有人可以帮我举一个例子来测试处理存储库中可分页对象的 Controller 吗?
是否有其他方法可以测试分页列表?请帮忙。
提前致谢!
最佳答案
您测试属性内容
。 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 实用程序类。通常我会像这里一样省略它们 https://github.com/EuregJUG-Maas-Rhine/site/blob/ea5fb0ca6e6bc9b8162d5e83a07e32d6fc39d793/src/test/java/eu/euregjug/site/web/IndexControllerTest.java#L172-L191
关于spring-mvc - 如何使用分页测试 Spring MVC Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44868320/