2012-03-09 163 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