简体   繁体   English

使用 spring-test-mvc 自定义 http 头测试

[英]Custom test of http header with spring-test-mvc

I'm testing my MVC service with spring-test-mvc I used something like:我正在使用spring-test-mvc测试我的 MVC 服务,我使用了类似的东西:

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 .例如,它可以是3500-3700而不是3600 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 .我试图弄清楚如何获取标头值并对其进行一些测试,而不是使用andExpect这种模式。

Perhaps you mean something like this.也许你的意思是这样的。

    MvcResult mvcResult = mvc.perform(get("/")).andReturn();
    String headerValue = mvcResult.getResponse().getHeader("headerName");

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):为 Admit 的回答添加更多细节:如果您还可以访问代码中的 JAX-RS 实现,则可以使用 CacheControl 对象进行非常明确的测试(例如使用 hamcrest 匹配器):

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

assertThat(maxAge, is(both(greaterThanOrEqualTo(3500)).and(lessThanOrEqualTo(3700))));

The best way is MockMvcResultMatchers.header() of spring-test最好的方法是 spring-test 的MockMvcResultMatchers.header()

mockMvc.perform(MockMvcRequestBuilders.get("/api"))
.andExpect(MockMvcResultMatchers.header()
.stringValues("count", "150"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM