Java 使用 spring-test-mvc 自定义 http 头测试
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19095996/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Custom test of http header with spring-test-mvc
提问by Avi
I'm testing my MVC service with spring-test-mvc
I used something like:
我正在使用以下内容测试我的 MVC 服务spring-test-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
. 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
.
现在我将缓存图像更改为特定范围内的随机图像。例如,代替3600
它可能是3500-3700
. 我试图弄清楚如何获取标头值并对其进行一些测试,而不是使用andExpect
.
采纳答案by Admit
Perhaps you mean something like this.
也许你的意思是这样的。
MvcResult mvcResult = mvc.perform(get("/")).andReturn();
String headerValue = mvcResult.getResponse().getHeader("headerName");
回答by Shawn Sherwood
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))));