How to send Cookie in MockHttpServletRequest

While writing test cases we might need to send Cookie in MockHttpServletRequest. In this post, we will see how to send Cookie with MockHttpServletRequest. The MockHttpServletRequest class is a Mock implementation of the HttpServletRequest interface and contains setCookies() method. The setCookie() method accepts the Cookie object as a parameter. You may get cookie value as null if you try to send them using headers.

public void setCookie(Cookie.. cookies)

Let’s see an example to add Cookie in MockHttpServletRequest

import javax.servlet.http.Cookie;

@RunWith(MockitoJUnitRunner.class)
public class TestClass {

    private MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();

    @Before
    public void setUp() {
        String cookieValue = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9";
        Cookie cookie = new Cookie("cookieToken",cookieValue);
        mockHttpServletRequest .setCookies(cookie );
    }
}

Another example using MockMvcResultbulders class.

@Autowired
private MockMvc mvc;
 
@Test
public void someUseCase() throws Exception 
{
  MvcResult mvcResult = mvc.perform( MockMvcRequestBuilders
      .get("/someuri")
      .accept(MediaType.APPLICATION_JSON))
      .cookie(cookie)
	  .contentType(MediaType.APPLICATION_JSON)
      .content(entity.tojson(false))).andReturn();
}	

We can also use thenReturn as below.

import javax.servlet.http.Cookie;

@RunWith(MockitoJUnitRunner.class)
public class TestClass {

    private MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();

    @Before
    public void setUp() {
        String cookieValue = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9";
        Cookie cookie = new Cookie("cookieToken",cookieValue);
        Mockito.when(mockHttpServletRequest .getCookies()).thenReturn(cookie);
    }
}

Additional information.

The Below code will not work.

@Test
public void someUseCase() throws Exception 
{
  MvcResult mvcResult = mvc.perform( MockMvcRequestBuilders
      .get("/someuri")
      .accept(MediaType.APPLICATION_JSON))
      .header(HttpHeaders.COOKIE,"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9")// Will not work
	.contentType(MediaType.APPLICATION_JSON)
      .content(entity.tojson(false))).andReturn();
}

The above code will not work. If we try to pass the cookie value in the header then request.getcookies() will returns null. In AbstractRememberMeService there is a method called extractRememberMeCookie() that is calling request.getCookies() method.

That’s all about how to send Cookie in MockHttpServletRequest.

Check other tutorials.