Java – use mockmvc to get the HttpServletRequest attribute

I have a very 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 use the mockmvc call in many different ways, but I couldn't provide the attribute "userid"

For example, with it, 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 tried this too, but I didn't succeed:

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 remoteuser, but I cannot set attributes mapping on HttpServletRequest

Any clues?

Solution

You can add request attributes by calling requestattr ^ ^

mockmvc.perform(get("/api/test").requestAttr("userId","testUserId")...
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>