title: Unable to mock a service to have it throw an exception
body: <p>I'm new to using Mockito for unit-testing Spring Rest controllers. Here is my controller and my test code.</p>
  
  <pre><code>@RestController
  @RequestMapping("/api/food/customer")
  public class CustomerController {
      @Autowired
      private CustomerService service;
  
      @RequestMapping(method=RequestMethod.POST, produces= MediaType.APPLICATION_JSON_VALUE)
      public ResponseEntity&lt;Customer&gt; addCustomer(@RequestBody Customer c){
          Logger log = LoggerFactory.getLogger(CustomerController.class.getName());
          try {
              service.addCustomer(c);
          } catch (UserNameException e){
              log.error("UserNameException", e);
              return new ResponseEntity(HttpStatus.BAD_REQUEST);
          } catch (Exception e){
              log.error("", e);
              return new ResponseEntity(HttpStatus.BAD_REQUEST);
          }
          log.trace("Customer added: " + c.toString());
          return new ResponseEntity(c, HttpStatus.CREATED);
      }
  }
  
  @RunWith(MockitoJUnitRunner.class)
  @WebMvcTest
  public class CustomerRestTest {
      private MockMvc mockMvc;
      @Mock
      private CustomerService customerService;
      @Mock
      private CustomerDao customerDao;
      @InjectMocks
      private CustomerController customerController;
  
      @Before
      public void setup(){
          this.mockMvc = MockMvcBuilders.standaloneSetup(customerController).build();
      }
  
      @Test
      public void testAddDuplicateCustomer() throws Exception {
          Customer myCustomer = mock(Customer.class);
          when(customerService.addCustomer(myCustomer)).thenThrow(UserNameException.class);
          String content = "{\"lastName\" : \"Orr\",\"firstName\" : \"Richard\",\"userName\" : \"Ricky\"}";
          RequestBuilder requestBuilder = MockMvcRequestBuilders.post("/api/food/customer").accept(MediaType.APPLICATION_JSON).
                  content(content).contentType(MediaType.APPLICATION_JSON);
          MvcResult result = mockMvc.perform(requestBuilder).andReturn();
          MockHttpServletResponse response = result.getResponse();
          assertEquals(HttpStatus.BAD_REQUEST.value(), response.getStatus());
      }
  }
  </code></pre>
  
  <p>I'm attempting to mock my service layer and have it throw my custom exception when <em>addCustomer</em> is called. I'm getting back HttpStatus.CREATED instead of BAD_REQUEST. What can I do differently with the service mock line (the one with thenThrow) that may work properly?</p>