Issue
I have a rest template that makes a call in a method in a service class like so:
public CustomerResponse someMethod() {
CustomerResponse response = restTemplate.exchange(url, HttpMethod.GET, null, CustomerRes.class).getBody();
return response;
}
When trying to mock the restTemplate in my test class, it keeps throwing a NullPointerException on the line where the mock restTemplate is called:
public void checkResponseIsNotNull() {
CustomerResponse customerResponseMock = mock(CustomerResponse.class);
when(restTemplate.exchange(url, HttpMethod.GET, null, CustomerResponse.class).getBody()).thenReturn(customerResponseMock);
CustomerResponse cr = service.someMethod();
Assert.assertNotNull(cr);
}
Why is NullPointer being thrown? I have mocked a RestTemplate before, just without the getBody() method which leads be to believe its that which is causing the null pointer.
Solution
You should add one more level of mocking:
CustomerResponse customerResponseMock = mock(CustomerResponse.class);
ResponseEntity reMock = mock(ResponseEntity.class);
when(reMock.getBody()).thenReturn(customerResponseMock);
when(restTemplate.exchange(url, HttpMethod.GET, null, CustomerResponse.class)).thenReturn(reMock);
CustomerResponse cr = service.someMethod();
Originally you were setting-up the ResponseEntity
only and the RestTemplate
still remained with the defaults.. thus returning null when exchange
has been called.
Answered By - Maciej Kowalski