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?
You need to cast the resulting
Flux
toMono
. There are two options depending on your use case:single()
ornext()
single()
operator picks the first element from theFlux
. 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 theFlux
to emit zero or more items. It just takes the first one and the rest are ignored.