我正在使用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模式。
发布于 2013-09-30 22:17:49
也许你指的是这样的东西。
MvcResult mvcResult = mvc.perform(get("/")).andReturn();
String headerValue = mvcResult.getResponse().getHeader("headerName");发布于 2013-10-25 03:49:43
在add的答案中添加更多细节:如果您还可以在代码中访问JAX-RS实现,则可以使用CacheControl对象进行非常显式的测试(使用hamcrest匹配器的示例):
int maxAge = CacheControl
.valueOf(mvcResult.getResponse().getHeader("Cache-Control"))
.getMaxAge();
assertThat(maxAge, is(both(greaterThanOrEqualTo(3500)).and(lessThanOrEqualTo(3700))));发布于 2021-06-09 16:56:54
最好的方法是使用MockMvcResultMatchers.header()的spring-test
mockMvc.perform(MockMvcRequestBuilders.get("/api"))
.andExpect(MockMvcResultMatchers.header()
.stringValues("count", "150"));https://stackoverflow.com/questions/19095996
复制相似问题