title: Mocking RestTemplateBuilder and RestTemplate in Spring integration test
body: <p>I have a REST resource that gets a <code>RestTemplateBuilder</code> injected to build a <code>RestTemplate</code>:</p>
  
  <pre><code>public MyClass(final RestTemplateBuilder restTemplateBuilder) {
      this.restTemplate = restTemplateBuilder.build();
  }
  </code></pre>
  
  <p>I would like to test that class. I need to mock the calls the <code>RestTemplate</code> makes to another service:</p>
  
  <pre><code>request = restTemplate.getForEntity(uri, String.class);
  </code></pre>
  
  <p>I tried this in my IT:</p>
  
  <pre><code>@RunWith(SpringRunner.class)
  @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
  public class MyIT {
  
  @Autowired
  private TestRestTemplate testRestTemplate;
  @MockBean
  private RestTemplateBuilder restTemplateBuilder;
  @Mock
  private RestTemplate restTemplate;
  
  @Test
  public void shouldntFail() throws IOException {
  
      ResponseEntity&lt;String&gt; responseEntity = new ResponseEntity&lt;&gt;(HttpStatus.NOT_FOUND);
      when(restTemplateBuilder.build()).thenReturn(restTemplate);
      when(restTemplate.getForEntity(any(URI.class), any(Class.class))).thenReturn(responseEntity);
  ...
  ResponseEntity&lt;String&gt; response = testRestTemplate.postForEntity("/endpoint", request, String.class);
    ...
  }
  }
  </code></pre>
  
  <p>When I run the test, I get the following exception:</p>
  
  <pre><code>java.lang.IllegalStateException: Failed to load ApplicationContext
  ...
  Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.test.web.client.TestRestTemplate': Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: RestTemplate must not be null
  </code></pre>
  
  <p>How do I do this correctly?</p>