Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MockMVC inject mockHttpServletRequest when not in method signature

Given I have inherited some Spring MVC controller code with signature

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public ModelAndView upload(HttpServletRequest request, HttpServletResponse response) {

  String remoteAddress = request.getRemotedAddr();
  auditService.logAddress(remoteAddress);

  // do work...

  return mav;
}

and I have a Spring MockMvc test that performs the test

public void someTest() {
    mockMvc().perform(fileUpload("/upload").file(FileFactory.stringContent("myFile")));

    // do work...
    verify(auditService.logAddress("123456"));
}

I need to set the remote address to "12345" on the HttpServletRequest object that is passed into my upload controller method, so I can verify the call to mock auditService in the test.

I can create a MockHttpServletRequest object and call the setRemoteAddr() method, but how to pass this mock request object to the mockMvc() method call?

like image 503
Ayub Malik Avatar asked Aug 28 '13 11:08

Ayub Malik


1 Answers

You can add a RequestPostProcessor. Which you can then pass in to the mockmvc stuff by using the with() method.

mockMvc().perform(
  fileUpload("/upload")
  .file(FileFactory.stringContent("myFile"))
  .with(new RequestPostProcessor() { 
    public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
       request.setRemoteAddr("12345"); 
       return request;
    }}));

Something like that should work.

like image 73
M. Deinum Avatar answered Oct 31 '22 03:10

M. Deinum