【问题标题】:How can one create fake FeignClient in Springboot?如何在 Spring Boot 中创建假的 Feign 客户端?
【发布时间】:2020-08-04 09:32:32
【问题描述】:

我有 Real FeignClient,它从远程端点返回一些对象。

但是,在我开始要求新服务之前,我需要先测试我的实体/逻辑。我决定造假 将返回我需要的对象的模拟服务(最多 5 个)。

如何在 SpringBoot 中伪造 FeignClient?

【问题讨论】:

标签: java spring spring-boot mocking


【解决方案1】:

您可以使用@Primary 注解覆盖默认实现。

在你的 java 配置文件中:

@Bean
@Primary // this anotation will override the system implementation
public FeignClient feignClient() {
 // create and return a fake FeignClient here.
return MyFakeImplementationFeignClient();
}

【讨论】:

    【解决方案2】:

    您可以使用真正的 FeignClient,但让它与虚拟服务器对话。

    一个简单的虚拟服务器是 Wiremock,您可以在您的 java 代码中启动它或作为一个独立的 java 主类:

    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)));
    

    【讨论】:

    • wiremock 可以返回实体吗?
    • wiremock 返回 HTTP 响应。如果您知道实体的编码方式(在 json 或 xml 中),您可以使用 .withBodyFile(filename) 或 .withBody(string) 编写自己的响应正文
    猜你喜欢
    • 1970-01-01
    • 2017-01-27
    • 2017-01-22
    • 2020-09-25
    • 1970-01-01
    • 2021-01-21
    • 2018-01-21
    • 1970-01-01
    • 2018-04-19
    相关资源
    最近更新 更多