Mocking RestTemplate exchange returns null

Viewed 34

I have looked at multiple posts here - one for example and tried multiple variations but still can't seem to be able to get a non-null value after mocking
RestTemplate#exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables).

I am not passing any uriVariables.

Here is my simplified source code:

RequestBody requestBody = new RequestBody(query,Collections.singletonMap("request", 
            request));   
HttpEntity<RequestBody> request = new HttpEntity<>(requestBody, createHttpHeaders());   
return restTemplate.exchange("http://localhost:8080/gql", HttpMethod.POST, request, 
JsonNode.class);

And the corresponding test code:

 @Mock
 private RestTemplate restTemplate;
 
 @InjectMocks
 private FetchDataService fetchDataService;
  
 @Test
 public void testFetchData() {
 when(restTemplate.exchange(anyString(), any(HttpMethod.class), any(HttpEntity.class), 
             any(Class.class)))
     .thenReturn(new ResponseEntity<>(expectedResponse, HttpStatus.OK));  
  ResponseEntity<JsonNode> response = fetchDataService.getData();   
  }

expectedResponse is a JsonNode instance above. The problem is that response always returns a null body.

I am able to verify that the call does happen if I use this -

  Mockito.verify(restTemplate)
     .exchange(anyString(), any(HttpMethod.class), any(HttpEntity.class), any(Class.class));

I'm using junit 5, spring boot 2.6.7, jdk 11 if that matters.

0 Answers
Related