title: Validating if request body in HTTP POST request is null in Spring Boot controller
body: <p>I am replacing manual validation of input to a POST request in a Spring Boot REST-controller. JSR-303 Spring Bean Validation is used for validating the instance variables in the request body and this is working as expected. What is the recommended method to validate that the object in the request body is not null?</p>
  
  <p>I have tried: </p>
  
  <ul>
  <li><p>annotating the entire object such as this: @NotNull @Valid @RequestBody Foo foo</p></li>
  <li><p>annotating the entire class with @NotNull </p></li>
  </ul>
  
  <p>I am replacing:</p>
  
  <pre class="lang-java prettyprint-override"><code>@PostMapping...
  public ResponseEntity&lt;Map&lt;String, Object&gt;&gt; editFoo(
  @RequestBody Foo foo, ...) {
     if(foo == null) {
        return (new ResponseEntity&lt;&gt;(headers, HttpStatus.BAD_REQUEST));
     }
  }
  </code></pre>
  
  <p>with a Bean Validation equivalent:</p>
  
  <pre class="lang-java prettyprint-override"><code>@PostMapping...
  public ResponseEntity&lt;Map&lt;String, Object&gt;&gt; editFoo(
  @Valid @RequestBody Foo foo, ...) {
     ...
  }
  </code></pre>
  
  <p>I tried unit testing the controller method by:</p>
  
  <pre class="lang-java prettyprint-override"><code>// Arrange
      Foo foo = null;
      String requestBody = objectMapper.writeValueAsString(foo);
  
      // Act + assert
      mockMvc
      .perform(
      post("/end_point")
      .contentType("application/json")
      .content(requestBody))
      .andExpect(status().isBadRequest());
  </code></pre>
  
  <p>I expected a MethodArgumentNotValidException which is handled by a @ControllerAdvice for this exception, but I get HttpMessageNotReadableException when executing the unit test.
  My questions:</p>
  
  <ol>
  <li>is it necessary to test if the request body is null?</li>
  <li>if 1. is true, how should this be done with Bean Validation?</li>
  </ol>