Testing Spring MVC Controller with Spring Data Pages


Since version 3.2, Spring MVC offers a nice way of testing controllers using the MockMvc class. Using MockMvc, your unit tests can test Spring Controllers with an emphasis on mocking a HTTP call instead of calling a specific method on the Controller class. You can find more about the MockMvc class on the Spring Documentation.

Spring Data offers an easy way to integrate any Spring-powered application to data sources of various types (from JPA to NoSQL). Amongst one of its interesting features, there's a seamless support for pagination. Spring Data offers support to automatically paginate your queries, parsing request parameters to create a paginated request via a PageableArgumentResolver (you can find more information at the documentation page).

The documentation - however - doesn't include how to configure a PageableArgumentResolver using the and - subsequentially - how to make sure that using parameters such as page and page.size are actually parsed in your tests that use MockMvc.

In order to register the PageableArgumentResolver in your XML setup, you can use this:

[gist id="f0eeb7896754a298cad9"]

And, in order to trigger the PageableArgumentResolver in your unit tests, you need to create your MockMvc like this:

[gist id="5570813"]