pass remoteUser value in HttpServletRequest to mockmvc perform test

a 夏天 提交于 2019-12-21 20:23:58

问题


I have an api call as:

@RequestMapping(value = "/course", method = RequestMethod.GET)
ResponseEntity<Object> getCourse(HttpServletRequest request, HttpServletResponse response) throwsException {
        User user = userDao.getByUsername(request.getRemoteUser());

}

I'm getting the user null when I call this from the test class like:

HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
 Mockito.when(request.getRemoteUser()).thenReturn("test1");

    MvcResult result =  mockMvc.perform( get( "/course")
                    .contentType(MediaType.APPLICATION_JSON)
                    .andExpect( status().isOk() )
                    .andExpect( content().contentType( "application/json;charset=UTF-8" ) )
                    .andReturn();

When I debug request object I can see remoteUser=null. So how can I pass the value to remote user?


回答1:


You can use RequestPostProcessor in order to modify the MockHttpServletRequest in any fashion you want. In your case:

mockMvc.perform(get("/course").with(request -> {
                    request.setRemoteUser("USER");
                    return request;
                })...

And if you're stuck with older versions of Java:

mockMvc.perform(get("/course").with(new RequestPostProcessor() {
            @Override
            public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
                request.setRemoteUser("USER");
                return request;
            }
        })...


来源:https://stackoverflow.com/questions/35162679/pass-remoteuser-value-in-httpservletrequest-to-mockmvc-perform-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!