【发布时间】:2012-03-09 20:39:50
【问题描述】:
我正在尝试为我的一种方法编写集成测试,以处理表单提交。
问题是我在控制器的@RequestMapping 中使用了@PathVariable int id。
当我的测试方法到达 .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());
}
【问题讨论】:
-
你能发布你的方法的定义(源代码,而不是测试)吗?
-
请发布您的控制器和您的测试。我假设您在测试中使用了 MockHttpServletRequest 和 annotationMethodHandlerAdapter.handle。
-
我已经用示例代码更新了问题,希望对您有所帮助。
标签: spring testing spring-mvc mocking integration-testing