Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting httpServletRequest attribute with MockMvc

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?

like image 949
Andrea Girardi Avatar asked Feb 05 '16 10:02

Andrea Girardi


2 Answers

You add a request attribute by calling requestAttr ^^

mockMvc.perform(get("/api/test").requestAttr("userId", "testUserId")...
like image 155
a better oliver Avatar answered Nov 17 '22 21:11

a better oliver


You could use

mvc.perform(post("/api/v1/...")
    .with(request -> {
      request.addHeader(HEADER_USERNAME_KEY, approver);
      request.setAttribute("attrName", "attrValue");
      return request;
    })
    .contentType(MediaType.APPLICATION_JSON)...
like image 43
tsunllly Avatar answered Nov 17 '22 19:11

tsunllly