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

升级spring-boot-starter-parent至3.3.3后,WebTestClient的@SpringBootTest测试失败

问题原因与排查解决方法

问题根源

NoOpResponseErrorHandler类在Spring Framework 6.1.x(对应Spring Boot 3.3.x)版本中已被移除,替代方案是使用DefaultResponseErrorHandler.createNoOp()静态方法。你的测试启动时意外触发了TestRestTemplate的Bean创建,而该类在新版本中依赖的NoOpResponseErrorHandler已不存在,因此抛出NoClassDefFoundError。

为什么会创建TestRestTemplate?

  1. Spring Boot 3.3自动配置逻辑调整:当使用webEnvironment = RANDOM_PORT时,即便项目引入了spring-boot-starter-webflux,部分Servlet相关的自动配置类(比如TestRestTemplateAutoConfiguration)仍可能被意外激活,导致Spring尝试创建TestRestTemplate Bean。
  2. 依赖冲突:项目可能间接引入了旧版spring-web依赖,或者同时存在spring-web(Servlet栈)和spring-webflux(Reactive栈)的混合依赖,引发类路径混乱,触发错误的自动配置。

排查与解决步骤

  • 排查依赖树:执行mvn dependency:tree命令,检查是否有第三方库引入旧版本spring-web,或是否存在spring-web与spring-webflux的版本冲突。若发现冲突,排除多余的spring-web依赖。
  • 禁用TestRestTemplate自动配置:在测试类的@SpringBootTest注解中显式排除相关配置,阻止Spring创建不需要的Bean:
    @SpringBootTest(webEnvironment = RANDOM_PORT, classes = MyServiceApplication.class,
                    exclude = TestRestTemplateAutoConfiguration.class)
    public class MyClientTest {
        // ... 测试代码
    }
    
  • 显式激活WebTestClient配置:在测试类上添加@AutoConfigureWebTestClient注解,确保Spring优先激活Reactive测试相关配置,而非Servlet栈的TestRestTemplate配置:
    @SpringBootTest(webEnvironment = RANDOM_PORT, classes = MyServiceApplication.class)
    @AutoConfigureWebTestClient
    public class MyClientTest {
        // ... 测试代码
    }
    
  • 检查自定义配置:排查项目中的测试基类、自定义@Configuration类,确认是否有代码主动注入TestRestTemplate或触发其初始化逻辑,如有则移除或调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 02:16:02