5

I am in process of writing a junit for one of the controller methods with method signature as below:

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

I need to call this method using MockMvc and I am able to call using below:

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

But the problem is I am unable to setup HttpServletRequest Parameter while calling the original method using mock mvc. Without setting HttpServletRequest argument, my test is giving issues since it is something required and used with in original method.

Please let me know how should I setup the same. Thanks!

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
k_b
  • 343
  • 3
  • 16

1 Answers1

4

The idea is that you shouldn't need to.

MockMvcRequestBuilders#post(..) returns a MockHttpServletRequestBuilder which lets you construct the request with any values you want. These will be mirrored in the HttpServletRequest that gets passed to your handler method.

For example, you used

.contentType(MediaType.APPLICATION_JSON)

this will set the content-type header of the request. In your handler method, if you did

request.getHeader("content-type");

you'd get back a corresponding String for the MediaType.APPLICATION_JSON.

The MockHttpServletRequestBuilder has "setters" for every part of the request.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • Ohh yes.. Got it. I wanted to add attribute in session inside request which I am able do using below: MockHttpSession session = new MockHttpSession(); session.setAttribute("username", "kb@test.com"); MockHttpServletRequestBuilder mockBuilder = post("/user/getTokenizedURL.json").contentType(MediaType.APPLICATION_JSON).content(json).session(session).servletPath("/user/getTokenizedURL.json"); mockMvc.perform(mockBuilder).andDo(print()).andExpect(status().isOk()); Many Thanks Sotirios!!! – k_b Nov 18 '15 at 23:37