[英]How can one create fake FeignClient in Springboot?
我有 Real FeignClient,它从远程端点返回一些对象。
但是,在我开始要求新服务之前,我需要先测试我的实体/逻辑。 我决定创建一个虚假的模拟服务,它将返回我需要的对象(最多 5 个)。
我如何在 SpringBoot 中伪造 FeignClient?
您可以使用 @Primary 注释来覆盖默认实现。
在您的 java 配置文件中:
@Bean
@Primary // this anotation will override the system implementation
public FeignClient feignClient() {
// create and return a fake FeignClient here.
return MyFakeImplementationFeignClient();
}
你可以使用真正的 FeignClient,但让它与一个虚拟服务器对话。
一个简单的虚拟服务器是 Wiremock,您可以使用 java 代码或作为独立的 java 主 class 启动:
http://wiremock.org/docs/java-usage/
WireMockServer wireMockServer = new WireMockServer("localhost", 8090);
wireMockServer.start();
WireMock.configureFor("localhost", 8090);
WireMock.stubFor(get(urlEqualTo("/somethings"))
.willReturn(aResponse()
.withBodyFile("path/to/test.json")));
启动并配置好之后,在 FeignClient 中使用http://localhost:8090 。
一个主要优点是您可以立即实现/测试 JSON 或 HTTP 映射,因此您也可以确定 FeignClient 配置正确。 您甚至可以模拟错误或延迟:
WireMock.stubFor(get(urlEqualTo("/somethings")).willReturn(
aResponse()
.withStatus(503)
.withFixedDelay(10_000)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.