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

使用@WebMvcTest测试RestaurantController时为何需要UserService Bean

问题原因

@WebMvcTest作为MVC层切片测试,默认会扫描加载项目中所有标注了@EnableWebSecurity的安全配置类。你自定义的SecurityConfig类构造方法依赖注入了UserService,Spring在初始化SecurityConfig的时候必须先实例化UserService,所以即使你仅测试RestaurantController,上下文加载阶段也会因为找不到UserService的Bean抛出异常。你配置的@AutoConfigureMockMvc(addFilters = false)仅会禁用过滤器链的执行,不会阻止SecurityConfig类本身的实例化,因此不解决Bean缺失的问题。

解决方案
  • 方案1:直接Mock UserService
    在测试类中新增一行@MockBean UserService userService;即可,Spring会自动生成UserService的Mock实例注入到SecurityConfig中,不需要额外配置,改造成本最低。
  • 方案2:测试时排除SecurityConfig加载
    修改@WebMvcTest注解,排除自定义安全配置类的扫描:
@WebMvcTest(controllers = RestaurantController.class,
    excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = SecurityConfig.class))

该方案不会加载安全配置,完全不需要相关依赖Bean,适合不需要安全逻辑的MVC测试场景。

额外注意

你的测试代码中getAllRestaurants用例的断言jsonPath("$[2].name", is("Jane Doe"))和你预设的第三个餐厅名称"Adriano's pizza"不一致,上下文问题解决后运行测试会触发断言失败,需要根据实际需求修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 10:00:03