You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Spring WebFlux测试中通过WebTestClient返回Mono?

解决WebTestClient获取Mono的问题

你的端点返回Mono<Person>,但当前代码用returnResult得到的是Flux,有两种常用方式获取Mono类型:

方法一:直接使用expectBody().returnMono()

这是最贴合场景的方式,因为你的接口返回单个对象,WebTestClient的expectBody专门处理这种单响应体的情况,配合returnMono可以直接拿到目标类型:

Mono<Person> personMono = webTestClient.get().uri("/persons/{id}", id)
        .exchange()
        .expectStatus().isOk()
        .expectBody(Person.class)
        .returnMono();

方法二:将Flux转换为Mono

如果已经通过returnResult拿到了Flux,也可以通过Reactor的操作符将其转为Mono:

  • 使用next():获取Flux中的第一个元素,返回Mono,即使没有元素也会返回空Mono
  • 使用single():确保Flux中只有一个元素,否则会抛出NoSuchElementException或IllegalArgumentException

示例代码:

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

// 方式1:取第一个元素
Mono<Person> personMono1 = personFlux.next();

// 方式2:确保只有一个元素
Mono<Person> personMono2 = personFlux.single();

推荐使用第一种方法,它更符合你接口返回Mono<Person>的语义,代码也更简洁直观。

内容的提问来源于stack exchange,提问作者Katlock

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 12:52:03