使用MockMvc获取httpServletRequest属性

时间:2016-02-05 10:35:39

标签: java spring spring-mvc junit mockmvc

我有一个非常简单的控制器以这种方式定义:

DataGridView.CellPainting

我试图以许多不同的方式使用MockMvc调用,但是,我无法提供属性“userId”。

例如,有了它,它不起作用:

@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());
    }
    [....]
}

我也试过了,但没有成功:

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

在这种情况下,我可以设置RemoteUser,但不能在HttpServletRequest上设置属性映射。

有任何线索吗?

3 个答案:

答案 0 :(得分:8)

您可以通过调用requestAttr ^^

添加请求属性
mockMvc.perform(get("/api/test").requestAttr("userId", "testUserId")...

答案 1 :(得分: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);
}

//测试方法

@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));
}

答案 2 :(得分:0)

您可以使用

mvc.perform(post("/api/v1/...")
    .with(request -> {
      request.addHeader(HEADER_USERNAME_KEY, approver);
      request.setAttribute("attrName", "attrValue");
      return request;
    })
    .contentType(MediaType.APPLICATION_JSON)...