17

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?

Andrea Girardi
  • 4,337
  • 13
  • 69
  • 98

3 Answers3

25

You add a request attribute by calling requestAttr ^^

mockMvc.perform(get("/api/test").requestAttr("userId", "testUserId")...
a better oliver
  • 26,330
  • 2
  • 58
  • 66
1

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)...
tsunllly
  • 1,568
  • 1
  • 13
  • 15
0
@ResponseStatus(HttpStatus.OK)
@GetMapping(Routes.VALIDATE_EMAIL_TOKEN + "/validate")
public String validateEmailToken(@RequestParam(value = "token") String token,
                                 HttpServletRequest httpServletRequest) throws RestServiceException {
    return credentionChangeService.getUserByToken(token, httpServletRequest);
}

//test method

@Mock
private HttpServletRequest httpServletRequest
@Mock
private MerchantCredentialsChangeService mockCredentionChangeService;

@Test
public void testValidateEmailToken() throws Exception {
    final String token = "akfkldakkadjfiafkakflkd";
    final String expectedUsername = "9841414141";

    Mockito.when(mockCredentionChangeService.getUserByToken(Matchers.eq(token), Matchers.any(HttpServletRequest.class)))
            .thenReturn(expectedUsername);

    mockMvc.perform(get(Routes.VALIDATE_EMAIL_TOKEN + "/validate")
            .param("token", token))
            .andExpect(status().isOk())
            .andExpect(MockMvcResultMatchers.content().string(expectedUsername));
}
Milan Paudyal
  • 519
  • 9
  • 11