Getting httpServletRequest attribute with MockMvc

16,396

Solution 1

You add a request attribute by calling requestAttr ^^

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

Solution 2

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)...
Share:
16,396
Andrea Girardi
Author by

Andrea Girardi

For the glory, for the money and for the fun. Mostly for the money! Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. IT errors are like snowflakes They didn't drop the ball. They dropped the ball, kicked the coach in the nuts and took a crap in the quarterback's mouth If they see a scrambled mass of code that looks like it was written by a bevy of drunken sailors, then they are likely to conclude that the same inattention to detail pervades every other aspect of the project http://www.andreagirardi.it https://twitter.com/bazingaaaa

Updated on June 15, 2022

Comments

  • Andrea Girardi
    Andrea Girardi almost 2 years

    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?

    • M. Deinum
      M. Deinum about 8 years
      parameter != attribute.
  • Arvind Kumar
    Arvind Kumar almost 4 years
    this saved my day. i was wasting my time since morning. Thank you