Dave
Dave

Reputation: 19220

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

I'm using Spring 4.3.8.RELEASE. In my integration test, I'm using SPring's MockMvc framework, set up like so ...

@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))

what I cannot figure out is how to set the server name of my request. That is, when my controller is invoked that populates

final HttpServletRequest request

How do I set

request.getServerName() 

from the MockMvc call?

Upvotes: 1

Views: 2431

Answers (1)

Muralidharan.rade
Muralidharan.rade

Reputation: 2346

With RequestPostProcessor we can setup MockHttpServletRequest and mock up data.

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

Upvotes: 7

Related Questions