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

@WebfluxTest与@TestContainers集成测试行为差异原因咨询

Webflux控制器测试:@WebfluxTest与集成测试的线程调度差异

我实现了如下Webflux控制器方法:

public Mono<ResultDto> translate(final Flux<String> body,
                                 final String userId) {
    return userRepository.findByUserId(userId) // 返回language对象
            .publishOn(Schedulers.boundedElastic())
            .switchIfEmpty(
                    Mono.defer(() -> {
                                final Language language = Language.of(userId);
                                log.info("Mono Defer");
                                return userRepository.save(language); //返回language对象
                            })
                            .publishOn(Schedulers.boundedElastic()))
            .log("after switch if empty")
            .map(language -> translatorService.createTranslator(language))
            .map(cipher -> body.map(language::translate))
            .flatMap(flux -> proxyService.relayEntry(flux));
}

不同场景下的测试表现:

  • 当两次使用.publishOn(Schedulers.boundedElastic())时,@WebfluxTest和基于@TestContainers的集成测试表现均符合预期。
  • 移除Mono.defer()中的第二个.publishOn(Schedulers.boundedElastic())后:
    • @WebfluxTest表现正常
    • 集成测试出现异常:当findByUserId返回空Mono时,switchIfEmpty()后的代码始终在主线程组执行;若findByUserId返回非空Mono,则能正常在boundedElastic-1线程执行。
  • 移除findByUserId(userId)后的第一个.publishOn(Schedulers.boundedElastic()),保留最后一个时:
    • 当findByUserId返回空Mono时,"Mono Defer"日志在Reactor主线程输出,而"after switch if empty"日志则在boundedElastic-1线程输出。

目前两次使用.publishOn(Schedulers.boundedElastic())能保证所有场景符合预期,但我想了解为何@WebfluxTest与集成测试的表现会存在差异?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 09:02:12