Spring WebFlux, unit testing Mono and Flux
Asked Answered
E

2

9

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.

Epizoic answered 13/8, 2018 at 20:54 Comment(4)
Interesting question. I'm afraid it may end up as primarily opinion-based, but as I'm not especially familiar with WebFlux there may be a helpful best practice here.Omaromara
Thanks. Of course it will be opinion-based, but the web tends to say that there is no other clean way than testing it with the WebTestClient. So either I am searching in the wrong way or there is no other way.Epizoic
Have you read the testing section of Project Reactor Reference?Basset
Yes. My problem was (see answer) more about testing the body of a ServerResponseEpizoic
E
5

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

Epizoic answered 17/8, 2018 at 12:28 Comment(1)
Note that it doesn't yet work with Kotlin very well (issue)Headward
M
4

It depends on what exactly you want to test, for regular method you should use StepVerifier in favor of consume the output of you test. However router functions are unique, because, usually return a serverResponse that contains your data on body, so in that case its better use webClient or webTestClient.

Maillot answered 12/7, 2019 at 22:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.