【问题标题】:Getting httpServletRequest attribute with MockMvc使用 MockMvc 获取 httpServletRequest 属性
【发布时间】:2016-02-05 10:35:39
【问题描述】:

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

@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 上的属性映射。

有什么线索吗?

【问题讨论】:

  • 参数 != 属性。

标签: java spring spring-mvc junit mockmvc


【解决方案1】:

通过调用requestAttr ^^

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

【讨论】:

  • 这拯救了我的一天。我从早上开始就在浪费时间。谢谢
【解决方案2】:

你可以使用

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

【讨论】:

    【解决方案3】:
    @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));
    }
    

    【讨论】:

      猜你喜欢
      • 2010-09-22
      • 2016-02-29
      • 1970-01-01
      • 2017-09-16
      • 1970-01-01
      • 1970-01-01
      • 2018-02-07
      • 2013-09-12
      • 1970-01-01
      相关资源
      最近更新 更多