title: How to mock RestTemplate with Client or Server errors?
body: <p>I'm using a <code>restTemplate.postForEntity()</code> in my code.
  When testing the class around it, I use Mockito to mock RestTemplate.</p>
  
  <p><code>Mockito.when(restTemplate.postForEntity(.....)).thenReturn(response)</code></p>
  
  <p>where response is:</p>
  
  <p><code>ResponseEntity&lt;String&gt; response = new ResponseEntity(HttpStatus.UNAUTHORIZED);</code></p>
  
  <p>Now, when I run this test, the <code>postForEntity</code> returns the mock response I just showed. However, in real executions, the RestTemplate throws a <code>RestClientException</code> when it receives a <code>401</code> from the remote. </p>
  
  <p>Under the hood this is because <code>doExecute()</code> in <code>RestTemplate</code> checks for errors and throws an this exception in case of 4XX and 5XX errors.</p>
  
  <p>I can of course rewrite the mock rule:</p>
  
  <p><code>Mockito.when(restTemplate.postForEntity(.....)).thenThrow(new RestClientException(..))</code>.</p>
  
  <p>But in when reading the test this is not very intuitive: I would like it to response to a 401 or a 500 itself.</p>
  
  <p>What should I do to accomplish this?</p>