2015-11-17 16 views
1

我在寫的JUnit用如下的方法簽名與控制器的方法之一的製作工序的檢驗方法論證:設定的HttpServletRequest的使用MvcMock

@RequestMapping(value="/getTokenizedURL.json",method=RequestMethod.POST) 
@ResponseBody 
public ResponseData getTokenizedURL(@RequestBody final RequestData requestData, final HttpServletRequest request) throws CustomException 

我需要使用MockMvc調用這個方法,我可以使用以下調用:

mockMvc.perform(post("/user/getTokenizedURL.json") 
    .contentType(MediaType.APPLICATION_JSON) 
    .content(json)) 
    .andDo(print()) 
    .andExpect(status().isOk()); 

但問題是我無法設置HttpServletRequest參數調用時使用模擬MVC中的原始方法。沒有設置HttpServletRequest的說法,我的測試給出的問題,因爲它是必需的東西,並在原始方法中使用。

請讓我知道我應該如何設置相同。謝謝!

回答

2

這個想法是你不應該需要。

MockMvcRequestBuilders#post(..)返回MockHttpServletRequestBuilder它允許您用任何您想要的值構造請求。這些將被鏡像到傳遞給您的處理程序方法的HttpServletRequest中。

例如,使用

.contentType(MediaType.APPLICATION_JSON) 

這將設置請求的content-type報頭。在你的處理方法,如果你沒有

request.getHeader("content-type"); 

你會回來的MediaType.APPLICATION_JSON相應String

MockHttpServletRequestBuilder對請求的每個部分都有「設置者」。

+0

Ohh yes ..明白了。我想添加屬性在會議裏面請求,我可以使用下面: MockHttpSession session = new MockHttpSession(); session.setAttribute(「username」,「[email protected]」); (「/ user/getTokenizedURL.json」)。contentType(MediaType.APPLICATION_JSON).content(json).session(session).servletPath(「/ user/getTokenizedURL.json」); ()())。和Expect(status()。isOk()); 許多感謝Sotirios! –

相關問題