I want to mock RestTemplate object which is calling another microservice and receiving configuration for a particular device:
ResponseEntity<ConfigurationResponse> configurationResponse = restTemplate
.getForEntity("http://localhost:8081/configuration/serial/" + dto.getSerNum(), ConfigurationResponse.class);
I am mocking above RestTemplate like:
mockServer.expect(requestTo(
"http://localhost:8081/configuration/serial/" + device.getSerNum()))
.andExpect(method(HttpMethod.GET))
.andRespond(withSuccess(toJson(
ConfigurationResponse.builder()
.ip("192.168.1.1")
.netMask("255.255.0.0")
.build()),
MediaType.APPLICATION_JSON_UTF8));
but after the test start I am receiving an exception:
org.springframework.web.client.ResourceAccessException: I/O error on GET request for "http://localhost:8081/configuration/serial/XXX-BBB-KKK": Connection refused: connect; nested exception is java.net.ConnectException: Connection refused: connect
I am instantiating RestTemplate and MockRestServiceServer like:
class DeviceServiceTest {
private DeviceService deviceService;
private DeviceRepository deviceRepository = mock(DeviceRepository.class);
private RestTemplate restTemplate = new RestTemplate();
private MockRestServiceServermockServer = MockRestServiceServer.createServer(restTemplate);
@BeforeEach
void setUp() {
deviceService = new DeviceService(deviceRepository);
mockServer = MockRestServiceServer.createServer(restTemplate);
restTemplate = new RestTemplate();
}
}
I used below example from link below how-mock-rest-request
but it did not bring a desirable effect. I will be grateful for a piece of advice on how to fix my mock to establish a connection in my test.
EDIT
Basing on the topic click I know that I suppose to have the same bean of RestTemplate in service and in the test but honestly I don't know how to make it happened. I am instantiating a RestTemplate object in a method which I am testing.