title: Spring Controller testing with MockMvc post method
body: <p>I am trying to test a method of my controller in a Spring Boot application. This is a post endpoint, which gets an id in a request and it passes on this id to a service:</p>
  
  <pre><code>@Slf4j
  @Controller
  public class AdministrationController {
  
      private final AdministrationService administrationService;
  
      @Autowired
      public AdministrationController(AdministrationService administrationService) {
          this.administrationService = administrationService;
      }
  
      @PostMapping("/administration")
      public @ResponseBody ResponseEntity&lt;String&gt; deleteByMessageId(String id) {
          return new ResponseEntity&lt;&gt;(administrationService.deleteMessageById(id), HttpStatus.OK);
      }
  }
  </code></pre>
  
  <p>The test for this method of the controller:</p>
  
  <pre><code>RunWith(SpringRunner.class)
  @WebMvcTest(AdministrationController.class)
  public class AdministrationControllerTest {
  
      @Autowired
      private MockMvc mvc;
  
      @MockBean
      private AdministrationService service;
  
      @Test
      public void 
      deleteByMessageId_whenCalled_thenServiceMethodIsCalledWithRequestParameters() throws Exception {
  
          Object randomObj = new Object() {
              public final String id = "1234";
          };
  
          ObjectMapper objectMapper = new ObjectMapper();
          String json = objectMapper.writeValueAsString(randomObj);
  
  
          MvcResult result = mvc.perform(
              post("/administration")
                      .contentType(MediaType.APPLICATION_JSON)
                      .content(json))
              .andExpect(status().isOk())
              .andReturn();
  
          verify(service, times(1)).deleteMessageById("1234");
  }
  </code></pre>
  
  <p>}</p>
  
  <p>When I run this test, the post request is executed, but with an empty body:</p>
  
  <pre><code>MockHttpServletRequest:
    HTTP Method = POST
    Request URI = /administration
     Parameters = {}
        Headers = {Content-Type=[application/json]}
           Body = &lt;no character encoding set&gt;
  Session Attrs = {}
  </code></pre>
  
  <p>It seems, even though I set the content in my test, it does not appear in the request I am sending.
  And, indeed, the test fails:</p>
  
  <pre><code>Argument(s) are different! Wanted: "1234"
  Actual invocation has different arguments: null
  </code></pre>
  
  <p>What am I missing here? How can I set the request body with MockMvc?</p>