You need to enable JavaScript to run this app. JUnit5 Spring Security WebMvcTest 报PasswordEncoder类型bean不存在问题
优惠活动
大模型
产品
解决方案
定价
更多

JUnit5 Spring Security WebMvcTest 报PasswordEncoder类型bean不存在问题

问题根因

  1. @WebMvcTest 默认仅加载指定控制器相关的组件,不会主动加载你自定义的WebSecurityConfig配置类,因此配置类中定义的PasswordEncoder Bean 不会被初始化,触发第一个找不到Bean的报错。
  2. 当你通过@MockBean 模拟了PasswordEncoder 后,Spring会初始化ActuatorWebSecurityConfigurationAdapter 配置类,该类中依赖的management.endpoints.web.access.password 属性在测试环境没有配置对应值,会注入为null,触发第二个空指针报错。

解决方法

方案1(推荐,仅测试控制器逻辑时使用)

跳过安全过滤器加载,不需要处理安全相关依赖,直接在测试类上加@AutoConfigureMockMvc(addFilters = false) 即可:

@ExtendWith(SpringExtension.class)
@WebMvcTest(EntryOverviewController.class)
@AutoConfigureMockMvc(addFilters = false) // 新增注解跳过安全过滤器
class EntryOverviewControllerTest {

    @Autowired
    private MockMvc mvc;

    @WithMockUser(value = "user")
    @Test
    public void testCorrectModel() throws Exception {
      mvc.perform(get(ApplicationConstants.URL_ENTRY_OVERVIEW)).andExpect(status().isOk()).andExpect(model().attributeExists("registerEntry"))
                .andExpect(view().name(ApplicationConstants.VIEW_ENTRY_OVERVIEW));
    }
}

方案2(需要保留安全逻辑测试时使用)

给测试补充缺失的配置属性,避免空指针:

@ExtendWith(SpringExtension.class)
@WebMvcTest(EntryOverviewController.class)
// 注入测试用的配置值
@TestPropertySource(properties = {
    "management.endpoints.web.access.user=test",
    "management.endpoints.web.access.password=test123"
})
class EntryOverviewControllerTest {

    @Autowired
    private MockMvc mvc;
    
    @MockBean
    private PasswordEncoder passwordEncoder;

    @WithMockUser(value = "user")
    @Test
    public void testCorrectModel() throws Exception {
      mvc.perform(get(ApplicationConstants.URL_ENTRY_OVERVIEW)).andExpect(status().isOk()).andExpect(model().attributeExists("registerEntry"))
                .andExpect(view().name(ApplicationConstants.VIEW_ENTRY_OVERVIEW));
    }
}

方案3(不需要加载Actuator配置时使用)

测试时排除Actuator相关的安全配置类,避免加载不必要的组件:

@ExtendWith(SpringExtension.class)
@WebMvcTest(controllers = EntryOverviewController.class, 
            excludeFilters = @ComponentScan.Filter(
                type = FilterType.ASSIGNABLE_TYPE, 
                classes = ActuatorWebSecurityConfigurationAdapter.class
            ))
@Import(WebSecurityConfig.class) // 导入你需要的安全配置
class EntryOverviewControllerTest {

    @Autowired
    private MockMvc mvc;

    @WithMockUser(value = "user")
    @Test
    public void testCorrectModel() throws Exception {
      mvc.perform(get(ApplicationConstants.URL_ENTRY_OVERVIEW)).andExpect(status().isOk()).andExpect(model().attributeExists("registerEntry"))
                .andExpect(view().name(ApplicationConstants.VIEW_ENTRY_OVERVIEW));
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 21:06:04