Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom test of http header with spring-test-mvc

Tags:

I'm testing my MVC service with spring-test-mvc I used something like:

MockMvc mockMvc = standaloneSetup(controller).build();
mockMvc.perform(get("<my-url>")).andExpect(content().bytes(expectedBytes)).andExpect(content().type("image/png"))
       .andExpect(header().string("cache-control", "max-age=3600"));

Which worked fine.

Now I changed the cache image to be random in a specific range. For example, instead of 3600 it could be 3500-3700. I'm trying to figure out how I can get the header value and do some tests on it instead of using this pattern of andExpect.

like image 787
Avi Avatar asked Sep 30 '13 13:09

Avi


3 Answers

Perhaps you mean something like this.

    MvcResult mvcResult = mvc.perform(get("/")).andReturn();
    String headerValue = mvcResult.getResponse().getHeader("headerName");
like image 193
Admit Avatar answered Sep 21 '22 13:09

Admit


To add a little more detail to Admit's answer: if you also have access to a JAX-RS implementation in your code, you can use the CacheControl object to make a very explicit test (example using hamcrest matchers):

int maxAge = CacheControl
                .valueOf(mvcResult.getResponse().getHeader("Cache-Control"))
                .getMaxAge();

assertThat(maxAge, is(both(greaterThanOrEqualTo(3500)).and(lessThanOrEqualTo(3700))));
like image 20
Shawn Sherwood Avatar answered Sep 24 '22 13:09

Shawn Sherwood


The best way is MockMvcResultMatchers.header() of spring-test

mockMvc.perform(MockMvcRequestBuilders.get("/api"))
.andExpect(MockMvcResultMatchers.header()
.stringValues("count", "150"));
like image 5
Valeriane Avatar answered Sep 25 '22 13:09

Valeriane