Spring mvc 隔离控制器测试can';t实例化可分页的

Spring mvc 隔离控制器测试can';t实例化可分页的,spring-mvc,testing,spring-data,spring-mvc-test,Spring Mvc,Testing,Spring Data,Spring Mvc Test,我有一个Spring MVC控制器,它使用Spring数据的分页支持: @Controller public class ModelController { private static final int DEFAULT_PAGE_SIZE = 50; @RequestMapping(value = "/models", method = RequestMethod.GET) public Page<Model> showModels(@Pageable

我有一个Spring MVC控制器,它使用Spring数据的分页支持:

@Controller
public class ModelController {

    private static final int DEFAULT_PAGE_SIZE = 50;

    @RequestMapping(value = "/models", method = RequestMethod.GET)
    public Page<Model> showModels(@PageableDefault(size = DEFAULT_PAGE_SIZE) Pageable pageable, @RequestParam(
            required = false) String modelKey) {

//..
        return models;
    }

}
这种方法适用于其他不需要分页的控制器,但通过这种方法,我得到了一个很好的长Spring堆栈跟踪。它抱怨无法实例化Pageable:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.data.domain.Pageable]: Specified class is an interface
at   
.... lots more lines
问题:我如何更改测试,使magic No Request参数正确转换为Pageable

注意:在实际应用中,一切正常。

原始答案:

pageable的问题可以通过提供自定义参数处理程序来解决。如果设置了此选项,则将在ViewResolver异常(循环)中运行。要避免这种情况,必须设置ViewResolver(例如匿名JSON ViewResolver类)

更新(2020年): 不再需要添加
viewsolver

关于平行答案:
在没有
ApplicationContext
和/或好友的情况下运行此测试无法解决原始问题。

只需为测试添加@EnableSpringDataWebSupport即可。就这样。

对于spring boot,只需添加为我解决的ArgumentResolver:

从触发错误的代码:

this.mockMvc = MockMvcBuilders.standaloneSetup(weightGoalResource).build();
对于这一点,有效的方法是:

this.mockMvc = MockMvcBuilders.standaloneSetup(weightGoalResource)
            .setCustomArgumentResolvers(new PageableHandlerMethodArgumentResolver())
            .build();

我在测试类中添加了
@EnableSpringDataWebSupport
注释,但没有任何效果。你能详细说明一下这是怎么回事吗-现在,1应该是正确的答案。如果单元测试仍然失败,请检查返回的错误是否不同。可能是你换了一个不同的错误。为什么会这样?你能给我更多的解释,这样我就能更好地理解当这种情况再次发生时如何克服它吗?:-)将@EnableSpringDataWebSupport添加到测试类并不能解决我的问题-仍然是相同的异常:
没有为接口org.springframework.data.domain.Pageable找到主构造函数或默认构造函数。这取决于某个包吗?Sooo。。。。我不得不删除@DataJpaTest并将后端应用程序移到更高一级。
this.mockMvc = MockMvcBuilders.standaloneSetup(weightGoalResource).build();
this.mockMvc = MockMvcBuilders.standaloneSetup(weightGoalResource)
            .setCustomArgumentResolvers(new PageableHandlerMethodArgumentResolver())
            .build();