I am using Mockito in JUnit and I have a method making a request to a microservice using RestTemplate.
private static final String REQUESTOR_API_HOST = "http://localhost:8090/requestor/v1/requestors/";
public TokenRequestorPayload getTokenRequestor(Long id) {
restClient = new RestTemplate();
return restClient.getForObject(REQUESTOR_API_HOST + id, TokenRequestorPayload.class);
}
This method returns a JSON object which will be deserialize in TokenRequestorPayload class.
When I execute unit tests they fail because mock didn't work and I got a org.springframework.web.client.ResourceAccessException. How can I mock my RestTemplate?
Test
RestTemplate restTemplate = Mockito.spy(RestTemplate.class);
Mockito.doReturn(this.tokenRequestorMockJson()).when(restTemplate).getForObject(Mockito.anyString(), Mockito.eq(TokenRequestorPayload.class));
Error
org.springframework.web.client.ResourceAccessException: I/O error on GET request for "http://localhost:8090/requestor/v1/requestors/1": Connection refused (Connection refused); nested exception is java.net.ConnectException: Connection refused (Connection refused)