我想模拟RestTemplate对象,该对象正在调用另一个微服务并接收特定设备的配置:
ResponseEntity<ConfigurationResponse> configurationResponse = restTemplate
.getForEntity("http://localhost:8081/configuration/serial/" + dto.getSerNum(), ConfigurationResponse.class);
我在RestTemplate上面嘲笑,例如:
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));
但是在测试开始后,我收到一个异常:
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
我正在像实例化RestTemplate和MockRestServiceServer
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();
}
}
我在下面的链接中使用了以下示例 how-mock-rest-request
但是没有带来令人满意的效果。 对于如何修复模拟程序以在测试中建立连接,我将不胜感激。
编辑
基于主题click,我知道我应该在服务和测试中使用相同的RestTemplate bean,但是老实说,我不知道如何实现它。我正在测试的方法中实例化RestTemplate对象。