JUnit5 Spring Security WebMvcTest 报PasswordEncoder类型bean不存在问题
问题根因
@WebMvcTest默认仅加载指定控制器相关的组件,不会主动加载你自定义的WebSecurityConfig配置类,因此配置类中定义的PasswordEncoderBean 不会被初始化,触发第一个找不到Bean的报错。- 当你通过
@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
相关产品推荐
相关产品推荐

