title: Junit: mockMvc headers don't allow to use Cookies?
body: <p>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 <code>customData</code> data is placed inside the <code>Cookie</code> header.
  This is the code for my simple test:</p>
  <pre><code>@Test
      public void myFristTest() throws Exception {
          mockMvc.perform(MockMvcRequestBuilders.post(MY_URL)
                  .header(&quot;Cookie&quot;, &quot;customData=customString&quot;)
                  .accept(MediaType.APPLICATION_JSON_VALUE)
                  .contentType(MediaType.APPLICATION_JSON_VALUE)
                  .content(ConversionUtil.objectToString(BODY_OF_MY_REQUEST)))
                  .andExpect(status().isCreated());
      }
  </code></pre>
  <p>Unfortunately <strong>this test fails</strong>. The Java code that goes to test is the following:</p>
  <pre><code>String customData;
  Cookie[] cookies = request.getCookies();
          
          if (cookies != null) {
              for (Cookie cookie : cookies) {
                  if (cookie.getName().equals(&quot;customData&quot;)) {
                      customData = cookie.getValue();
                  }
              }
          }
  
  if(customData != null) {
      // code that returns HTTP status isCreated
  } else {
      throw new HttpServerErrorException(HttpStatus.FOUND, &quot;Error 302&quot;); 
  }
  </code></pre>
  <p>In practice, it seems that the <code>customData</code> string, which should be taken from the request header <code>Cookie</code>, is not found! So the test <strong>only evaluates the else branch</strong> 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 <code>.header(&quot;Cookie&quot;, &quot;customData=customString&quot;)</code> in my test doesn't do what I want, that is, <strong>it doesn't set the header cookie correctly</strong>, which is why my method fails.  <strong>How do I do a proper test that really inserts Cookie header into the request?</strong>
  I use Junit 4.</p>