Junit:mockMvc headers 不允许使用 Cookies?

Junit: mockMvc headers don't allow to use Cookies?

我正在测试使用 Java 和 Spring Boot 编写的应用程序,我有一个问题。 我的测试模拟了一个 HTTP 请求,只有 customData 数据放在 Cookie header 中才有效。 这是我简单测试的代码:

@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"); 
}

实际上,似乎没有找到应该从请求header Cookie中取出的customData字符串!所以测试 只评估 else 分支 并且实际上也在堆栈跟踪中告诉我测试期望状态 isCreated 但状态 302 给出。 这怎么解释,因为应用程序(未经测试)有效?我想 .header("Cookie", "customData=customString") 在我的测试中没有做我想做的事情,也就是说,它没有正确设置 header cookie,这就是为什么我的方法失败。 如何进行真正将 Cookie header 插入请求的正确测试? 我使用 Junit 4.

MockHttpServletRequestBuilder class 提供内部创建的 cookie builder method to add cookies. The MockHttpServletRequest 用于测试忽略通过 header 方法添加的“Cookie” headers。

所以创建一个 Cookie 并添加它

Cookie cookie = new Cookie("customData", "customString");

mockMvc.perform(MockMvcRequestBuilders.post(MY_URL)
        .cookie(cookie)
        .accept(MediaType.APPLICATION_JSON_VALUE)
        .contentType(MediaType.APPLICATION_JSON_VALUE)
        .content(ConversionUtil.objectToString(BODY_OF_MY_REQUEST)))
        .andExpect(status().isCreated());