java – 使用MockMvc获取httpServletRequest属性
作者:互联网
我有一个非常简单的控制器以这种方式定义:
@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上设置Attributes映射.
任何线索?
解决方法:
您可以通过调用requestAttr ^^来添加请求属性
mockMvc.perform(get("/api/test").requestAttr("userId", "testUserId")...
标签:mockmvc,java,spring,spring-mvc,junit 来源: https://codeday.me/bug/20190727/1556086.html