wishyouwerehere
wishyouwerehere

Reputation: 253

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

I am testing an application written with Java and Spring Boot and I have a question. My test simulates an HTTP request which is valid only if the customData data is placed inside the Cookie header. This is the code for my simple test:

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

Unfortunately this test fails. The Java code that goes to test is the following:

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

In practice, it seems that the customData string, which should be taken from the request header Cookie, is not found! So the test only evaluates the else branch and actually also in the stacktrace tells me that the test was expecting the status isCreated but the status 302 is given. How can this be explained, since the application (without test) works? I imagine that .header("Cookie", "customData=customString") in my test doesn't do what I want, that is, it doesn't set the header cookie correctly, which is why my method fails. How do I do a proper test that really inserts Cookie header into the request? I use Junit 4.

Upvotes: 4

Views: 6287

Answers (1)

Savior
Savior

Reputation: 3531

The MockHttpServletRequestBuilder class provides the cookie builder method to add cookies. The MockHttpServletRequest created internally for the test ignores "Cookie" headers added through the header method.

So create a Cookie and add it

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());

Upvotes: 7

Related Questions