Issue
I am working on a non-spring application and using restTemplate feature from spring-web.While writing Junit test i am unable to mock response from restTemplate.postForEntity(). What am i doing wrong here.
Below is the function
public JsonObject apiResponse(Request request) throws JsonProcessingException {
String queryRequest = objectMapper.writeValueAsString(request);
HttpHeaders headers = new HttpHeaders();
headers.add("content-type", "application/json");
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> responseEntity = restTemplate.postForEntity(
"https://testurl/test/",
new HttpEntity<>(queryRequest, headers), String.class);
return JsonParser.parseString(Objects.requireNonNull(responseEntity.getBody())).getAsJsonObject();
Below is the Junit
@ExtendWith(MockitoExtension.class)
public class HandlerTest {
@Spy
@InjectMocks
Handler handler;
@Mock
RestTemplate restTemplate;
@Test
public void apiREsponseTest() throws JsonProcessingException {
//this is not working
Mockito.doReturn(new ResponseEntity <>("test", HttpStatus.OK))
.when(restTemplate).postForEntity(eq("test"), eq(HttpEntity.class), eq(String.class));
assertNotNull(handler.apiResponse(request));
Solution
RestTemplate restTemplate = new RestTemplate();
This is not getting mocked as it's a local object and it will always call the real method. You can try this to mock the restTemplate:
RestTemplate restTemplate = getRestTemplate();
protected RestTemplate getRestTemplate() {
return new RestTemplate();
}
//Add this stub to your test
when(handler.getRestTemplate()).thenReturn(restTemplate);
The URL is hardcoded here:
ResponseEntity<String> responseEntity = restTemplate.postForEntity(
"https://testurl/test/",
new HttpEntity<>(queryRequest, headers), String.class);
Hence the you need to change your stubbing as well.
Mockito.doReturn(new ResponseEntity <>("test", HttpStatus.OK))
.when(restTemplate).postForEntity(eq("https://testurl/test/"), eq(HttpEntity.class), eq(String.class));
Making these changes should make your test green hopefully. Let me know if this doesn't resolve your issue.
Answered By - Rahul Dey
Answer Checked By - Clifford M. (JavaFixing Volunteer)