隔离控制器测试无法实例化可分页
问题内容:
我有一个使用Spring-Data分页支持的Spring MVC控制器:
@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:
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的Controller一起使用,但是通过这种方法,我可以得到这些不错的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
问题:如何更改测试,以便神奇地执行“无请求参数到可分页”转换?
注意:在实际的应用程序中,一切正常。
问题答案:
可分页的问题可以通过提供自定义参数处理程序来解决。如果设置了此选项,则将在ViewResolver异常(循环)中运行。为了避免这种情况,您必须设置一个ViewResolver(例如,匿名JSON
ViewResolver类)。
mockMvc = MockMvcBuilders.standaloneSetup(controller)
.setCustomArgumentResolvers(new PageableHandlerMethodArgumentResolver())
.setViewResolvers(new ViewResolver() {
@Override
public View resolveViewName(String viewName, Locale locale) throws Exception {
return new MappingJackson2JsonView();
}
})
.build();