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

How do I set the request server name using Spring's MockMvc framework?

我正在使用 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))

我不知道如何设置请求的服务器名称。也就是说,当调用我的控制器时填充

final HttpServletRequest request

如何设置

request.getServerName() 

来自 MockMvc 调用?

使用 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;
        }
    }));