14

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

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

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

例如,这样它不起作用:

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

我也试过这个,但没有成功:

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(); 

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

有什么线索吗?

4

3 回答 3

21

requestAttr您通过调用^^添加请求属性

mockMvc.perform(get("/api/test").requestAttr("userId", "testUserId")...
于 2016-02-05T11:37:40.377 回答
1

你可以使用

mvc.perform(post("/api/v1/...")
    .with(request -> {
      request.addHeader(HEADER_USERNAME_KEY, approver);
      request.setAttribute("attrName", "attrValue");
      return request;
    })
    .contentType(MediaType.APPLICATION_JSON)...
于 2020-10-14T22:35:46.157 回答
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));
}
于 2019-05-20T07:21:51.573 回答