title: Unit Test POST with @WebMvcTest - @MockBean Service returns null
body: <p>I'm trying to unit test a controller to save a <code>Brand</code> entity. In this test, I'm creating a <code>Brand</code> that I expect to get back and then I'm posting JSON to the controller. Originally, I was relying on <code>pass-by-reference</code> so my controller method was basically doing:</p>
  
  <pre><code>@Override
  public ResponseEntity&lt;MappingJacksonValue&gt; save(@Valid @RequestBody Brand brand, BindingResult bindingResult) {
  
    validate(brand, null, bindingResult);
    if (bindingResult.hasErrors()) {
        throw new InvalidRequestException("Invalid Brand", bindingResult);
    }
  
    this.brandService.save(brand); // pass by reference
    MappingJacksonValue mappingJacksonValue = jsonView(JSON_VIEWS.SUMMARY.value, brand);
    return new ResponseEntity&lt;&gt;(mappingJacksonValue, HttpStatus.CREATED);
  }
  </code></pre>
  
  <p>Note that I wasn't actually using the returned <code>Brand</code> from the service. When I tested this way, my test was failing because the controller was returning the JSON I passed in, and since the service is mocked, the controller didn't return the brand I was expecting, which was to have an ID. So I changed the controller to do this:</p>
  
  <pre><code>brand = this.brandService.save(brand);
  </code></pre>
  
  <p>However, when I debug, the brand returned from the mocked service is null. Below is my test.</p>
  
  <pre><code>@RunWith(SpringRunner.class)
  @WebMvcTest(BrandController.class)
  public class BrandSimpleControllerTest {
  
    @Autowire
    private MockMvc mockMvc;
  
    @MockBean
    private BrandService brandService;
  
    @Test
    public void testSave() throws Exception {
      Brand brand = new Brand();
      brand.setId(1L);
      brand.setName("Test Brand");
  
      when(this.brandService.save(brand)).thenReturn(brand);
  
      this.mockMvc.perform(this.post("/api/brands")
        .content("{\"name\": \"Test Brand\"}"))
        .andExpect(jsonPath("$.id", is(1)))
        .andExpect(jsonPath("$.name", is("Test Brand")));
    }
  
  }
  </code></pre>
  
  <p>Any suggestions?</p>