【问题标题】:How to write Junit for a service component class using webtestclient in Spring 5如何在 Spring 5 中使用 webtestclient 为服务组件类编写 Junit
【发布时间】:2018-12-27 04:24:47
【问题描述】:

我在我的 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 测试控制器类方法,但不能在服务类中测试

【问题讨论】:

    标签: junit webclient spring-webflux


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-18
      • 1970-01-01
      • 1970-01-01
      • 2019-06-04
      • 2021-05-07
      • 1970-01-01
      • 2021-05-20
      相关资源
      最近更新 更多