【问题标题】:How do I set the request server name using Spring's MockMvc framework?如何使用 Spring 的 MockMvc 框架设置请求服务器名称?
【发布时间】:2017-11-06 22:52:04
【问题描述】:

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

【问题讨论】:

    标签: spring spring-mvc servlets junit mockmvc


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-13
      • 2010-09-07
      • 2018-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-24
      相关资源
      最近更新 更多