繁体   English   中英

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

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

我正在使用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"));

哪个工作得很好。

现在我将缓存图像更改为特定范围内的随机图像。 例如,它可以是3500-3700而不是3600 我试图弄清楚如何获取标头值并对其进行一些测试,而不是使用andExpect这种模式。

也许你的意思是这样的。

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

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

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

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

最好的方法是 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