如何在Spring WebFlux测试中使用webTestClient返回Mono?

问题描述 投票:0回答:1

我在 Spring WebFlux 中有一个 Rest 服务,它从

Mono<Person>
端点返回
/person/{id}

当我编写这样的 Junit 测试时,它期望来自 webTestClient 的 Flux,如下面的代码所示:

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

returnResult
方法返回一个
FluxExchangeResult<T>
,它返回一个
Flux
类型,而不是我期望的`Mono类型。

有办法得到

Mono
吗?

spring-webflux junit-jupiter
1个回答
0
投票

您需要将生成的

Flux
转换为
Mono
。根据您的使用情况,有两个选项:
single()
next()

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

single()
运算符从
Flux
中选取第一个元素。如果发出零个或多个元素,则会抛出错误。另一方面,
next()
运算符更加宽松,允许
Flux
发出零个或多个项目。它只需要第一个,其余的被忽略。

© www.soinside.com 2019 - 2024. All rights reserved.