Junit:mockMvc 标头不允许使用 Cookie?

wis*_*ere 4 java cookies junit http spring-mvc

我正在测试用 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());
    }
Run Code Online (Sandbox Code Playgroud)

不幸的是这个测试失败了。用于测试的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"); 
}
Run Code Online (Sandbox Code Playgroud)

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

Sav*_*ior 6

该类MockHttpServletRequestBuilder提供了添加 cookie 的cookie构建器方法。MockHttpServletRequest内部为测试创建的内容会忽略通过该方法添加的“Cookie”标头header

所以创建一个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());

Run Code Online (Sandbox Code Playgroud)