I have a REST resource that gets a RestTemplateBuilder
injected to build a RestTemplate
:
public MyClass(final RestTemplateBuilder restTemplateBuilder) {
this.restTemplate = restTemplateBuilder.build();
}
I would like to test that class. I need to mock the calls the RestTemplate
makes to another service:
request = restTemplate.getForEntity(uri, String.class);
I tried this in my IT:
@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<String> responseEntity = new ResponseEntity<>(HttpStatus.NOT_FOUND);
when(restTemplateBuilder.build()).thenReturn(restTemplate);
when(restTemplate.getForEntity(any(URI.class), any(Class.class))).thenReturn(responseEntity);
...
ResponseEntity<String> response = testRestTemplate.postForEntity("/endpoint", request, String.class);
...
}
}
When I run the test, I get the following exception:
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
How do I do this correctly?
MockitoAnnotations.initMocks(this)
– Masuria