【问题标题】:How to unit test a class that makes an external WebClient request?如何对发出外部 WebClient 请求的类进行单元测试?
【发布时间】:2019-07-27 18:09:02
【问题描述】:

我有一个@Service 类,它执行一些空值检查,然后使用 WebClient 调用外部微服务。 Sonar 抱怨这个类没有经过测试,因为该方法没有经过全面测试。问题是,我怎样才能模拟这个调用或为此使用模拟服务器?我已经尝试过 WebTestClient,但似乎无法正常工作..

public Mono<CartResponse> someServiceCall(BarRequest barRequest)

//some null checks and random logic.

return WebClient.create("http://" + fooHostName)
                .post()
                .uri(uri)
                .body(Mono.just(barRequest), BarRequest.class)
                .exchange()
                .flatMap(serviceResponse -> {
                    if (serviceResponse.statusCode().is5xxServerError()) {

                        //some error logic
                        return Mono.just(barResponse);
                    }
                    return serviceResponse.bodyToMono(BarResponse.class);
                });

所以我不想真正打这个电话,我只是想在测试中涵盖它,所以我想了解如何模拟或启动模拟服务器。我一直在现在大约一天..

【问题讨论】:

  • 你试过类似wiremock.org吗?
  • 我希望有一个内置的 spring 解决方案,类似于模拟 RestTemplate 调用的方式
  • 您可以添加您尝试使用模拟的代码

标签: spring-boot spring-webflux spring-test spring-webclient


【解决方案1】:

目前尚不支持像 RestTemplate 那样模拟 WebClient。

在 github 上有一个未解决的问题。

Support of MockRestServiceServer for WebClient

Spring 自己使用MockWebServer 来测试自己的代码,因此可以肯定地说这是一个可行的解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-13
    • 1970-01-01
    • 2015-06-01
    • 2013-06-10
    • 2023-03-20
    • 1970-01-01
    • 2019-05-04
    • 1970-01-01
    相关资源
    最近更新 更多