如何模拟在服务类构造函数中创建的WebClient

问题描述 投票:0回答:1

如何在下面的类的单元测试中模拟 webClient

@Service
public class Service {
  private final WebClient webClient;
  public Service(String baseUrl) {
    this.webClient = WebClient.builder().baseUrl(baseUrl).build();
  }
  public User getUser() { webClient.get().bodyToMono(User.class).block(); }
}
  1. ReflectionTestUtils 有效,有更好的方法吗?
  2. WebClient 没有构造函数注入
    Service(WebClient webClient)

有什么解决办法吗?

spring mockito junit5
1个回答
0
投票

通常在这种情况下,您可以将 WebClient 包装到包装服务中:

@Service
public class YourWrapperWebClient{
    private final WebClient webClient;
    // constructor..

    // methods you care about that return the same thing as the WebClient's
}

现在您可以将

YourWrapperWebClient
注入到您的服务类中。我们可以模拟
YourWrapperWebClient
,它间接模拟 WebClient。

© www.soinside.com 2019 - 2024. All rights reserved.