【发布时间】:2021-06-11 23:04:28
【问题描述】:
我正在测试一个用 Java 和 Spring Boot 编写的应用程序,我有一个问题。
我的测试模拟了一个 HTTP 请求,该请求仅在 customData 数据放在 Cookie 标头内时才有效。
这是我的简单测试的代码:
@Test
public void myFristTest() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.post(MY_URL)
.header("Cookie", "customData=customString")
.accept(MediaType.APPLICATION_JSON_VALUE)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(ConversionUtil.objectToString(BODY_OF_MY_REQUEST)))
.andExpect(status().isCreated());
}
很遗憾此测试失败。用于测试的 Java 代码如下:
String customData;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("customData")) {
customData = cookie.getValue();
}
}
}
if(customData != null) {
// code that returns HTTP status isCreated
} else {
throw new HttpServerErrorException(HttpStatus.FOUND, "Error 302");
}
在实践中,似乎没有找到应该从请求头Cookie获取的customData字符串!所以测试只评估 else 分支,实际上在堆栈跟踪中也告诉我测试期待状态 isCreated 但给出了状态 302。
由于应用程序(未经测试)有效,如何解释这一点?我想我的测试中的.header("Cookie", "customData=customString") 没有做我想要的,也就是说,它没有正确设置标题cookie,这就是我的方法失败的原因。 如何进行正确的测试,真正将 Cookie 标头插入到请求中?
我使用 Junit 4。
【问题讨论】:
标签: java http spring-mvc cookies junit