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

Spring Boot从3.2.5升级到3.3.0后WebMvcTest测试失败

解决思路
  • 调整WebMvcTest的组件扫描范围:Spring Boot 3.3可能收紧了WebMvcTest默认的组件扫描规则,导致自定义Filter未被纳入属性解析上下文。可以在@WebMvcTest注解中显式指定要包含的Filter类:

    @WebMvcTest(includeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = YourCustomFilter.class))
    
  • 验证Filter的注册有效性:检查自定义Filter类是否标注了@Component,或者配置类中注册Filter的@Bean方法是否在测试上下文生效。如果使用了@Conditional相关注解,确认测试环境满足触发条件。

  • 替换@Value为@ConfigurationProperties:改用配置绑定的方式更稳定,避免@Value在测试上下文的解析问题。

    1. 创建配置类:
      @ConfigurationProperties(prefix = "my.custom")
      public class MyCustomProperties {
          private String value;
          // getter/setter
      }
      
    2. 在启动类或配置类上添加@EnableConfigurationProperties(MyCustomProperties.class)
    3. 在Filter中注入该配置类:
      @Autowired
      private MyCustomProperties properties;
      
  • 确认测试属性文件的加载:检查application-test.properties是否位于src/test/resources目录下,属性键名是否拼写正确。也可以在测试类中显式指定属性源:

    @TestPropertySource(locations = "classpath:application-test.properties")
    

    或者先用@SpringBootTest替代@WebMvcTest验证属性是否能正常加载,排除WebMvcTest上下文的特殊限制。

  • 排查测试自动配置变更:Spring Boot 3.3可能对WebMvcTest的自动配置做了调整,尝试在测试类添加@AutoConfigureWebMvc注解,或者检查是否存在@MockBean导致上下文初始化异常,间接影响属性注入。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 14:54:55