我正在尝试为我的一个方法编写一个集成测试,用于处理表单提交。
问题是我在我的控制器的@PathVariable int id
中使用@RequestMapping
。
当我的测试方法到达.handle()部分时,我收到以下错误消息。
nested exception is java.lang.IllegalStateException: Could not find @PathVariable [id] in @RequestMapping
所以控制器无法达到id。我正在使用request.setRequestURI("/url-" + s.getId());
但显然它没有帮助设置@PathVariable
。
有没有办法设置我的Mock对象的@PathVariable
?
更新
是的,我在我的测试类中使用MockHttpServletRequest
和annotationMethodHandlerAdapter.handle
。
控制器:
@RequestMapping(method = RequestMethod.POST, params = {"edit" })
public String onSubmit(@ModelAttribute("sceneryEditForm") SceneryEditForm s,
@PathVariable int id, Model model) {
// some code that useing id
}
测试方法:
@Test
public void testEditButton() throws Exception {
MyObject s = new MyObject();
request.setMethod("POST");
request.setRequestURI("/edit-" + s.getId());
request.setParameter("edit", "set");
final ModelAndView mav = new AnnotationMethodHandlerAdapter()
.handle(request, response, controller);
assertViewName(mav, "redirect:/view-" + s.getId());
}
答案 0 :(得分:1)
错误是正确的:没有路径变量id
您需要使用占位符id
@RequestMapping(value = "/something/{id}",
method = RequestMethod.POST,
params = {"edit" })
public String onSubmit(@ModelAttribute("sceneryEditForm") SceneryEditForm s,
@PathVariable int id, Model model) {
// some code that useing id
}