junit - 如何在 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 测试控制器类方法,但不能在服务类中测试
解决方案
这应该在未来的 Spring Framework 版本中得到支持MockRestServiceServer
;参见SPR-15286。
目前,唯一的解决方案是为此使用单独的库,例如 okhttp 的MockWebServer
.
推荐阅读
- rebuild - 丢失副本后如何检查重建是否完成?
- java - 在 Corda 中将状态标记为已使用而不更改其内容
- ocr - Google Firebase MLKit Vision API 调整块边界
- spark-java - 如何在 Spark 嵌入式网络服务器中启用 HTTP/2
- c# - 如何像变量一样使用 DEBUG 常量
- c# - 如何更新列表中的单个数据/行
没有数据库 c# winforms - react-admin - 反应管理员 | 使用 ReferenceField 批量选择
- bash - 使用 awk 更改 CSV 文件的整列中的值
- c - 字符串正在使用键盘填充,但传递为空
- flutter - 如何在 Flutter 中将我的应用设置为横向模式?