Jen*_*der 37 testing spring-mvc spring-data spring-mvc-test
我有一个Spring MVC控制器,它使用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;
}
}
Run Code Online (Sandbox Code Playgroud)
我想使用漂亮的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());
}
}
Run Code Online (Sandbox Code Playgroud)
这种方法适用于其他控制器,它们不期望使用Pageable,但是有了这个,我得到了一个很好的长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
Run Code Online (Sandbox Code Playgroud)
问题:如何更改我的测试,以便正确进行神奇的No-Request-Parameter-To-Pageable转换?
注意:在实际应用中,一切正常.
mei*_*ier 43
可分页的问题可以通过提供自定义参数处理程序来解决.如果设置了此项,您将在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();
Run Code Online (Sandbox Code Playgroud)
小智 35
只需添加@EnableSpringDataWebSupport进行测试即可.而已.
对于春季启动,只需添加为我解决的ArgumentResolvers:
从触发错误的代码中:
this.mockMvc = MockMvcBuilders.standaloneSetup(weightGoalResource).build();
Run Code Online (Sandbox Code Playgroud)
对此有效:
this.mockMvc = MockMvcBuilders.standaloneSetup(weightGoalResource)
.setCustomArgumentResolvers(new PageableHandlerMethodArgumentResolver())
.build();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12609 次 |
| 最近记录: |