隔离控制器测试无法实例化可分页 [英] Isolated Controller Test can't instantiate Pageable
问题描述
我有一个 Spring MVC 控制器,它使用 Spring-Data 的分页支持:
I have a Spring MVC Controller which uses Pagination Support of Spring-Data:
@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 MVC 测试支持来测试 RequestMapping.为了使这些测试保持快速并与所有其他事情隔离开来,我不想创建完整的 ApplicationContext:
And I'd like to test the RequestMapping using the nice Spring MVC Test Support. In order to keep these tests fast and isolated from all the other stuff going on, I do not want to create the complete ApplicationContext:
public class ModelControllerWebTest {
private MockMvc mockMvc;
@Before
public void setup() {
ModelController controller = new ModelController();
mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
}
@Test
public void reactsOnGetRequest() throws Exception {
mockMvc.perform(get("/models")).andExpect(status().isOk());
}
}
这种方法可以很好地与其他不期望 Pageable 的控制器一起使用,但是通过这种方法,我得到了这些不错的长 Spring 堆栈跟踪之一.它抱怨无法实例化 Pageable:
This approach works fine with other Controllers, that do not expect a Pageable, but with this one I get one of these nice long Spring stacktraces. It complains about not being able to instantiate 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
问题:如何更改我的测试,以便神奇的 No-Request-Parameter-To-Pageable 转换正确发生?
Question: How do I change my test so the magic No-Request-Parameter-To-Pageable conversion happens properly?
注意:在实际应用中一切正常.
Note: In the actual application everything is working fine.
推荐答案
原答案:
pageable 的问题可以通过提供自定义参数处理程序来解决.如果设置了此项,您将在 ViewResolver 异常(循环)中运行.为避免这种情况,您必须设置一个 ViewResolver(例如匿名 JSON ViewResolver 类).
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();
更新(2020 年):不再需要添加 ViewResolver
.
关于平行答案:在没有 ApplicationContext
和/或朋友的情况下运行此测试并不能解决原始问题的问题.
Regarding the parallel answer:
It does not solve the problem for the original question to have this test running without ApplicationContext
and/or friends.
这篇关于隔离控制器测试无法实例化可分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!