如何在下面的类的单元测试中模拟 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(); }
}
Service(WebClient webClient)
有什么解决办法吗?
通常在这种情况下,您可以将 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。