2012-09-26 68 views
3

我的問題是如何調用這個。我可以做如何測試POST彈簧mvc

MyObject o = new MyObject(); 
myController.save(o, "value"); 

但這不是我想要做什麼。我希望MyObject處於請求發佈主體中?如何才能做到這一點?

@Requestmapping(value="/save/{value}", method=RequestMethod.POST) 
public void post(@Valid MyObject o, @PathVariable String value{ 
    objectService.save(o); 
} 

要說清楚我說的是單元測試。

編輯:

@RequestMapping(value = "/", method = RequestMethod.POST) 
public View postUser(ModelMap data, @Valid Profile profile, BindingResult bindingResult) { 

    if (bindingResult.hasErrors()) { 

     return dummyDataView; 
    } 


    data.put(DummyDataView.DATA_TO_SEND, "users/user-1.json"); 
    profileService.save(profile); 
    return dummyDataView; 
} 

回答

2

查看示例代碼演示了單元測試使用JUnit控制器和春季測試。

@RunWith(SpringJUnit4ClassRunner.class) 
@TestExecutionListeners({ 
     DependencyInjectionTestExecutionListener.class, 
     DirtiesContextTestExecutionListener.class, 
     TransactionalTestExecutionListener.class }) 
@Transactional 
@ContextConfiguration(locations = { 
    "classpath:rest.xml" 
    }) 
public class ControllerTest{ 
    private MockHttpServletRequest request; 
    private MockHttpServletResponse response; 



    @Autowired 
    private RequestMappingHandlerAdapter handlerAdapter; 

    @Autowired 
    private RequestMappingHandlerMapping handlerMapping; 

    @Before 
    public void setUp() throws Exception 
    { 
     this.request = new MockHttpServletRequest(); 
     request.setContentType("application/json"); 
     this.response = new MockHttpServletResponse(); 
    } 

    @Test 
    public void testPost(){ 
     request.setMethod("POST"); 
     request.setRequestURI("/save/test"); //replace test with any value 

     final ModelAndView mav; 
     Object handler; 

     try{ 
       MyObject o = new MyObject(); 
       //set values 
       //Assuming the controller consumes json 
       ObjectMapper mapper = new ObjectMapper(); 
       //set o converted as JSON to the request body 
       //request.setContent(mapper.writeValueAsString(o).getBytes()); 
       request.setAttribute("attribute_name", o); //in case you are trying to set a model attribute. 
       handler = handlerMapping.getHandler(request).getHandler(); 
       mav = handlerAdapter.handle(request, response, handler); 
       Assert.assertEquals(200, response.getStatus()); 
       //Assert other conditions. 
      } 
     catch (Exception e) 
      { 

      } 
    } 
} 
+0

非常感謝。必須是json嗎?我必須使用requestbody嗎? – pethel

+0

它可以轉換爲您的控制器接受的任何類型。形成數據,獲取字節並將其設置爲請求。 – FFL

+0

所以我可以做request.setContent(o); ? – pethel

0

您需要使用RequestBody:

@Requestmapping(value="/save/{value}", method=RequestMethod.POST) 
public void post(@RequestBody MyObject o, @PathVariable String value{ 
    objectService.save(o); 
} 

有關請求機構的文件一般信息:低於http://static.springsource.org/spring/docs/3.0.x/reference/mvc.html#mvc-ann-requestbody

+0

好的..也許......但假裝我正在使用它。我如何對此進行單元測試? – pethel

+0

你可以使用junit .. – insomiac