Isolated Controller Test can't instantiate Pageable

前端 未结 3 1554
小鲜肉
小鲜肉 2020-12-10 01:01

I have a Spring MVC Controller which uses Pagination Support of Spring-Data:

@Controller
public class ModelController {

    private static final int DEFAULT         


        
相关标签:
3条回答
  • 2020-12-10 01:09

    Original answer:

    The problem with pageable can be solved by providing a custom argument handler. If this is set you will run in a ViewResolver Exception (loop). To avoid this you have to set a ViewResolver (an anonymous JSON ViewResolver class for example).

    mockMvc = MockMvcBuilders.standaloneSetup(controller)
                .setCustomArgumentResolvers(new PageableHandlerMethodArgumentResolver())
                .setViewResolvers(new ViewResolver() {
                    @Override
                    public View resolveViewName(String viewName, Locale locale) throws Exception {
                        return new MappingJackson2JsonView();
                    }
                })
                .build();
    

    Updated (2020): It is not necessary to add the ViewResolver anymore.

    Regarding the parallel answer: It does not solve the problem for the original question to have this test running without ApplicationContext and/or friends.

    0 讨论(0)
  • 2020-12-10 01:21

    Just add @EnableSpringDataWebSupport for test. Thats it.

    0 讨论(0)
  • 2020-12-10 01:29

    For spring boot simply adding the ArgumentResolvers solved for me:

    From code which triggered the error:

    this.mockMvc = MockMvcBuilders.standaloneSetup(weightGoalResource).build();
    

    To this, which works:

    this.mockMvc = MockMvcBuilders.standaloneSetup(weightGoalResource)
                .setCustomArgumentResolvers(new PageableHandlerMethodArgumentResolver())
                .build();
    
    0 讨论(0)
提交回复
热议问题