etRequest中的remoteUser值传递给mockmvc

etRequest中的remoteUser值传递给mockmvc

本文介绍了将HttpServletRequest中的remoteUser值传递给mockmvc进行测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个api调用:

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

}

当我从测试类中调用该用户时,我得到的用户为null

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

当我调试请求对象时,我可以看到remoteUser=null.那么如何将值传递给远程用户?

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

推荐答案

您可以使用 RequestPostProcessor ,以便以您想要的任何方式修改MockHttpServletRequest.就您而言:

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

如果您仍然使用Java的旧版本:

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

这篇关于将HttpServletRequest中的remoteUser值传递给mockmvc进行测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 20:40