首页 > 解决方案 > 如何在 Spring 5 中使用 webtestclient 为服务组件类编写 Junit

问题描述

我在我的 Java 微服务中使用 Springboot2、Spring5 和 reactive-webflux。我有一个要使用 webtestclient 测试的服务类:-

@Service("authenticationProvider")
public class CommonAuthenticationProvider implements AuthenticationProvider {

 @Override
  public AccessToken getUserAccessToken(Tuple2<String, WebClient> serviceConnectionDetails, MultiValueMap<String, String> queryParams) {

    return serviceConnectionDetails._2
        .post()
        .uri(builder -> builder
            .path(serviceConnectionDetails._1)
            .queryParams(queryParams)
            .build())
        .accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML)
        .retrieve()
        .bodyToMono(AccessToken.class)
        .block();

  }
}

这里的 serviceConnectionDetails._2 是一个 webclient 实例。我想编写一个 JUnit 测试来模拟这个 webclient 并测试 getUserAccessToken() 方法。请帮忙,因为我尝试了很多东西,比如 mockmvc、mockRestServiceServer 但没有任何效果。后来我才知道,我不能使用 mockRestServiceServer,因为它曾经模拟 RestTemplate 而不是 WebClient。我可以使用 webtestclient 测试控制器类方法,但不能在服务类中测试

标签: junitwebclientspring-webflux

解决方案


这应该在未来的 Spring Framework 版本中得到支持MockRestServiceServer;参见SPR-15286

目前,唯一的解决方案是为此使用单独的库,例如 okhttp 的MockWebServer.


推荐阅读