title: How to write a test for a Controller which includes Errors / BindingResult?
body: <p>I'm working on a simple website using Spring Boot and Spring MVC, and I've come up against a scenario for which I can't manage to write a test. How do you test how the Controller deals with <code>Errors</code>, which affect the user interface, but aren't included in the <code>ModelAndView</code>?</p>
  
  <p>I was having trouble displaying error messages in my HTML form, and after much frustration I found it was because I was overwriting the Form object before returning it as an Object in the <code>ModelAndView</code>. </p>
  
  <p>This is the code in question </p>
  
  <pre><code>@PostMapping
  ModelAndView processPost(@Valid IdAndAmountForm idAndAmountForm, Errors errors) {
      if (errors.hasErrors()) {
          var beer = service.findBeerById(idAndAmountForm.getId());
          return new ModelAndView("beerView")
                  .addObject("beer", beer)
                  .addObject("idAndAmountForm", idAndAmountForm);
      } else {
          cart.add(idAndAmountForm);
          return new ModelAndView("redirect:/cart");
      }
  }
  </code></pre>
  
  <p>It works / behaves as expected, populating the <code>span</code> with the appropriate message when the HTML validation is removed.</p>
  
  <pre><code>    &lt;form th:action="@{/beer}" th:object="${idAndAmountForm}" method="post"&gt;
          &lt;label&gt;
              Amount
              &lt;span th:errors="*{amount}"&gt;&lt;/span&gt;
              &lt;input th:field="*{amount}" type="number" min="1" required&gt;
          &lt;/label&gt;
  </code></pre>
  
  <p>My mistake was in line 7 of the controller, where I previously had <code>.addObject("idAndAmountForm", new IdAndAmountForm());</code>
  There were no errors associated with the new form, so no error messages were displayed. Or that's what I think happened.</p>
  
  <p>Now how could I have written a test that detected this faulty behavior? 
  I spent some time dissecting the <code>Model</code>, looking for the error messages that I knew were somehow being passed to the Thymeleaf template, before concluding that the error messages were being handled separately by Spring. <a href="https://stackoverflow.com/a/11848621/8296287">This answer</a> helped me to see it was the <code>BindingResult</code> or <code>Errors</code> object that I wanted to check in my test. However, it's not part of the return value of any method I wrote. </p>
  
  <p>I suppose I could try to write a test for the <code>ViewResolver</code> or whatever automatically generated object intermediates between my controller and my template, or I could butcher my controller class to allow my test class to access the Errors. Both seem like bad ideas. The current solution is to consider the scenario too much effort to test, but I don't like to believe that this is untestable <em>in principle</em>.</p>