TheDarkLord
TheDarkLord

Reputation: 351

Set hostname in Spring MockMvc

Im writing an integration test using Spring MockMvc in SpringBoot and im trying to set the hostname, the default one is localhost, I would like it to be a valid domain name like localhost.com.

I prefer a way which uses minimal code so if its possible to achieve using yml file its awesome.

Upvotes: 1

Views: 2633

Answers (2)

Mohit Singh
Mohit Singh

Reputation: 524

You can run it as a spring-boot test with the following annotation and specify the hostname in properties.

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = {
        "HOSTNAME=mockhost",
})
public class IntegrationTest {

//test
}

Upvotes: 0

Ken Chan
Ken Chan

Reputation: 90497

When using MockHttpServletRequestBuilder to build the request , you can use with to define a RequestPostProcessor which further configure the MockHttpServletRequest :

  mockMvc.perform(MockMvcRequestBuilders
                .get("/foo")
                .with(req -> {
                    req.setServerName("localhost.com");
                    return req;
                }))
                .andExpect(status().isOk());

Upvotes: 3

Related Questions