Spring WebFlux,单元测试 Mono 和 Flux [英] Spring WebFlux, unit testing Mono and Flux

查看:132
本文介绍了Spring WebFlux,单元测试 Mono 和 Flux的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对反应式编程感兴趣,我玩了一下构建反应式 RESTful Web 服务 指南.并想向前移动并添加一些单元测试.

我尝试使用纯 Junit/Mockito 测试来测试我的处理程序 (RouterFunction).但是,因为它是响应式的,处理程序返回一个 Mono.所以我不得不 block() 它来测试 ServerResponse 状态,但无法提取他的身体来测试它.在网上搜索解决方案时,似乎所有示例都使用 WebTestClient.

我的问题是:

鉴于所有示例都使用 WebTestClient 来测试反应式 REST 服务,并且(单元)测试 ServerResponse 的主体并不容易.对 RouterFunction 进行单元测试是一个好习惯,还是总是使用 WebTestClient 进行更广泛的测试更好?

非常感谢.

解决方案

看来最好的做法是使用 WebTestClient.然而,这个可以在没有运行服务器的情况下使用;

<块引用>

spring-test 模块包含一个 WebTestClient,可用于测试 WebFlux 服务器端点有或没有正在运行的服务器..>

-- https://docs.spring.io/spring/docs/5.0.0.BUILD-SNAPSHOT/spring-framework-reference/html/web-reactive.html#web-reactive-tests

Interested in reactive programming, I played a bit with the Building a Reactive RESTful Web Service guide. And wanted to move forwrad and add some unit tests.

I tried to test my handler (RouterFunction) with plain Junit/Mockito test. But, because it is reactive, the handler returns a Mono<ServerResponse>. So I had to block() it to test the ServerResponse status but was not able to extract his body to test it. While searching the web for a solution, it seems that all the samples are using the WebTestClient.

My question is:

Given that all samples are using WebTestClient to test a reactive REST service and that it is not easier to (unit) test the body of a ServerResponse. Is it a good practice to unit test a RouterFunction or is it better to always do broader tests with the WebTestClient ?

Thanks a lot.

解决方案

It seems that the best practice is to use the WebTestClient. However this one can be used without a running server;

The spring-test module includes a WebTestClient that can be used to test WebFlux server endpoints with or without a running server.

-- https://docs.spring.io/spring/docs/5.0.0.BUILD-SNAPSHOT/spring-framework-reference/html/web-reactive.html#web-reactive-tests

这篇关于Spring WebFlux,单元测试 Mono 和 Flux的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆