Spring WebFlux,单元测试 Mono 和 Flux
Spring WebFlux, unit testing Mono and Flux
对响应式编程感兴趣,我玩了一下 Building a Reactive RESTful Web Service 指南。并想继续前进并添加一些单元测试。
我试图用简单的 Junit/Mockito 测试来测试我的处理程序 (RouterFunction
)。但是,因为它是反应式的,所以处理程序 returns a Mono<ServerResponse>
。所以我不得不 block()
它来测试 ServerResponse
状态,但无法提取他的 body 来测试它。在网上搜索解决方案时,似乎所有样本都使用 WebTestClient
.
我的问题是:
鉴于所有示例都使用 WebTestClient
来测试反应性 REST 服务,并且(单元)测试 ServerResponse
的 body 并不容易。对 RouterFunction
进行单元测试是一种好习惯,还是始终使用 WebTestClient
进行更广泛的测试更好?
非常感谢。
看来最好的做法是使用WebTestClient
。然而,这个可以在没有 运行 服务器的情况下使用;
The spring-test
module includes a WebTestClient
that can be used to test WebFlux server endpoints with or without a running server.
这取决于您究竟要测试什么,对于常规方法,您应该使用 StepVerifier 以支持使用您测试的输出。然而 路由器函数 是独一无二的,因为通常 return 一个 serverResponse 包含你在 body 上的数据,所以在那最好使用 webClient 或 webTestClient.
对响应式编程感兴趣,我玩了一下 Building a Reactive RESTful Web Service 指南。并想继续前进并添加一些单元测试。
我试图用简单的 Junit/Mockito 测试来测试我的处理程序 (RouterFunction
)。但是,因为它是反应式的,所以处理程序 returns a Mono<ServerResponse>
。所以我不得不 block()
它来测试 ServerResponse
状态,但无法提取他的 body 来测试它。在网上搜索解决方案时,似乎所有样本都使用 WebTestClient
.
我的问题是:
鉴于所有示例都使用 WebTestClient
来测试反应性 REST 服务,并且(单元)测试 ServerResponse
的 body 并不容易。对 RouterFunction
进行单元测试是一种好习惯,还是始终使用 WebTestClient
进行更广泛的测试更好?
非常感谢。
看来最好的做法是使用WebTestClient
。然而,这个可以在没有 运行 服务器的情况下使用;
The
spring-test
module includes aWebTestClient
that can be used to test WebFlux server endpoints with or without a running server.
这取决于您究竟要测试什么,对于常规方法,您应该使用 StepVerifier 以支持使用您测试的输出。然而 路由器函数 是独一无二的,因为通常 return 一个 serverResponse 包含你在 body 上的数据,所以在那最好使用 webClient 或 webTestClient.