Getting httpServletRequest attribute with MockMvc

Andrea Girardi picture Andrea Girardi · Feb 5, 2016 · Viewed 11.9k times · Source

I have a really simple controller defined in this way:

@RequestMapping(value = "/api/test", method = RequestMethod.GET, produces = "application/json")
public @ResponseBody Object getObject(HttpServletRequest req, HttpServletResponse res) {
    Object userId = req.getAttribute("userId");
    if (userId == null){
        res.setStatus(HttpStatus.BAD_REQUEST.value());
    }
    [....]
}

I tried to call using MockMvc in many different way but, I'm not able to provide the attribute "userId".

For instance, with this it doesn't work:

MockHttpSession mockHttpSession = new MockHttpSession(); 
mockHttpSession.setAttribute("userId", "TESTUSER");             
mockMvc.perform(get("/api/test").session(mockHttpSession)).andExpect(status().is(200)).andReturn(); 

I also tried this, but without success:

MvcResult result = mockMvc.perform(get("/api/test").with(new RequestPostProcessor() {
     public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
           request.setParameter("userId", "testUserId");
           request.setRemoteUser("TESTUSER");
           return request;
     }
})).andExpect(status().is(200)).andReturn(); 

In this case, I can set the RemoteUser but never the Attributes map on HttpServletRequest.

Any clue?

Answer

a better oliver picture a better oliver · Feb 5, 2016

You add a request attribute by calling requestAttr ^^

mockMvc.perform(get("/api/test").requestAttr("userId", "testUserId")...