Search code examples
spring-webfluxjunit-jupiter

How to return a Mono using webTestClient in Spring WebFlux testing?


I have a Rest service in Spring WebFlux that returns a Mono<Person> from a /person/{id} endpoint.

When I write my Junit test such as this it is expecting a Flux from the webTestClient as my code below shows:

Flux<Person> personFlux = webTestClient.get().uri("/persons/"+id)
                .exchange().expectStatus().isOk().returnResult(Person.class).getResponseBody();

The returnResult method is returning a FluxExchangeResult<T> which gives back a Flux type instead of a `Mono type I am expecting.

Is there a way to get Mono instead?


Solution

  • You need to cast the resulting Flux to Mono. There are two options depending on your use case: single() or next()

    Mono<Person> personMono = webTestClient.get().uri("/persons/" + id)
                    .exchange().expectStatus().isOk()
                    .returnResult(Person.class)
                    .getResponseBody()
                    .single(); // or next()
    

    single() operator picks the first element from the Flux. If zero or more than one element is emitted it will throw an error. On the other hand, next() operator is more lenient and allows the Flux to emit zero or more items. It just takes the first one and the rest are ignored.