2012-03-09 125 views
0

我正在尝试为我的一个方法写一个集成测试,它处理表单提交。 问题是我在我的控制器的@RequestMapping中使用@PathVariable int id。 当我的测试方法到达.handle()部分时,我收到以下错误消息。Spring @PathVariable集成测试

nested exception is java.lang.IllegalStateException: Could not find @PathVariable [id] in @RequestMapping 

所以控制器不能达到id。我使用的是request.setRequestURI("/url-" + s.getId());,但是它的设置并不方便@PathVariable。 有没有办法设置我的Mock对象的@PathVariable

更新:

呀,IM期运用MockHttpServletRequestannotationMethodHandlerAdapter.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()); 
    } 
+3

你可以发布你的方法的定义(源代码,而不是测试)? – 2012-03-09 21:30:03

+1

请发布您的控制器和您的测试。我假设你在测试中使用了MockHttpServletRequest和annotationMethodHandlerAdapter.handle。 – chrislovecnm 2012-03-10 08:38:35

+0

我已经更新了示例代码的问题,希望有所帮助。 – Sorex 2012-03-10 10:49:23

回答

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 
} 
+0

dang!谢谢您的帮助!不知何故,我只使用@PathVariable在GET ... – Sorex 2012-03-10 13:55:13