2

I am facing a problem to test a controller with pagination for my Spring boot MVC web project which uses Thymeleaf . My controller is as follows:

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

    }

I have tried with this following test segment which will count the contents items (initially it will return 0 item with pagination).

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

but getting this following error ( test was fine, before pagination):

 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)

I have goggled but no luck here. Can anybody help me with an example to test a controller which deals with pageable object from repository?

Is there any alternate way exist to test list with pagination? Please help.

Thanks in advance!

mnhmilu
  • 2,327
  • 1
  • 30
  • 50

2 Answers2

3

your testing the attribute contents. contents is of type Page as you added it under that name into the model (model.addAttribute("contents", results);) Page has no attribute size, it isn't a list.

You want to check for the total number of elements instead:

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

I have included the Hamcrest utility classes for your convenience. Usually I omit them like here https://github.com/EuregJUG-Maas-Rhine/site/blob/ea5fb0ca6e6bc9b8162d5e83a07e32d6fc39d793/src/test/java/eu/euregjug/site/web/IndexControllerTest.java#L172-L191

Michael Simons
  • 4,640
  • 1
  • 27
  • 38
2

Your "contents" in model it's not collection type , it's Page type. So you should use semantic for Page class not for Collection. From Page semantic it's getTotalElements() so it's pojo field totalElements in model

andExpect(model().attribute("contents", Matchers.hasProperty("totalElements", equalTo(0L))));
xyz
  • 5,228
  • 2
  • 26
  • 35