如何使用 Spring 的 MockMvc 框架设置请求服务器名称?

Dav*_*ave 1 junit spring servlets spring-mvc mockmvc

我正在使用 Spring 4.3.8.RELEASE。在我的集成测试中,我使用的是 SPring 的 MockMvc 框架,设置如下......

@Autowired 
private WebApplicationContext wac;

private MockMvc mockMvc;
...
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
...
    mockMvc.perform(get(contextPath + "/path") 
                    .contextPath(contextPath)
                    .principal(auth)
                    .param("param1", param1)
                    .param("param2", param2))
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚的是如何设置我的请求的服务器名称。也就是说,当我的控制器被调用时填充

final HttpServletRequest request
Run Code Online (Sandbox Code Playgroud)

我如何设置

request.getServerName() 
Run Code Online (Sandbox Code Playgroud)

来自 MockMvc 调用?

Mur*_*ade 6

使用RequestPostProcessor,我们可以设置MockHttpServletRequest和模拟数据。

    mockMvc.perform(get(contextPath + "/path").contextPath(contextPath).principal(auth).param("param1", param1).param("param2", param2).with(new RequestPostProcessor() {
        public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
            request.setServerName("system");
            return request;
        }
    }));
Run Code Online (Sandbox Code Playgroud)