In my tests I setup the MockMvc
object in the @Before
like this
mockMvc = MockMvcBuilders.webAppContextSetup(context)
.apply(springSecurity())
.build();
In every request I do I always need to send the same headers.
Is there a way to configure the headers the MockMvc
will use globally or per test class?
Finally, an accept header is set to tell the endpoint the client expects a JSON response. Lines 10 to 15 use statically imported methods from MockMvcResukltMatchers to perform assertions on the response. We begin by checking that the response code returned is 201 'Created' and that the content type is JSON.
The class will handle the HTTP request and pass it further to our controller. Controller code will be executed in exactly the same way as if it was processing the real request, just without the cost of starting a web server. MockMvc also carries several useful methods for performing requests and asserting on results.
Spring boot MockMVC example Learn to use Spring MockMVC to perform integration testing of Spring webmvc controllers. MockMVC class is part of Spring MVC test framework which helps in testing the controllers explicitly starting a Servlet container.
The process for using MockMVC is setting up a MockMVC object: . . . } [/sourcecode]Once we have the MockMVC object, we can start building a request and then test expectations on the response. } [/sourcecode]This simple test checks that a GET request to /index.do returns a 2xx response.
You can write an implementation of javax.servlet.Filter
. In your case, you can add the headers into your request. MockMvcBuilders
has a method to add filters:
mockMvc = MockMvcBuilders.webAppContextSetup(context)
.apply(springSecurity())
.addFilter(new CustomFilter(), "/*")
.build();
How about you make a factory class to start you off with your already decrorated-with-headers request? Since MockHttpServletRequestBuilder
is a builder, you just decorate the request with any of the additional properties (params, content type, etc.) that you need. The builder is designed just for this purpose! For example:
public class MyTestRequestFactory {
public static MockHttpServletRequestBuilder myFactoryRequest(String url) {
return MockMvcRequestBuilders.get(url)
.header("myKey", "myValue")
.header("myKey2", "myValue2");
}
}
Then in your test:
@Test
public void whenITestUrlWithFactoryRequest_thenStatusIsOK() throws Exception {
mockMvc()
.perform(MyTestRequestFactory.myFactoryRequest("/my/test/url"))
.andExpect(status().isOk());
}
@Test
public void whenITestAnotherUrlWithFactoryRequest_thenStatusIsOK() throws Exception {
mockMvc()
.perform(MyTestRequestFactory.myFactoryRequest("/my/test/other/url"))
.andExpect(status().isOk());
}
Each test will call the endpoint with the same headers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With