问题
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.
回答1:
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 aWebTestClient
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
回答2:
According project reactor, you should use StepVerifier in favor of consume the outuput of you test. You could find a good explain about it here, and source is here.
来源:https://stackoverflow.com/questions/51830411/spring-webflux-unit-testing-mono-and-flux