控制器测试报错:springSecurityFilterChain为NullBean类型异常排查
问题分析
出现BeanNotOfRequiredTypeException: Bean named 'springSecurityFilterChain' is expected to be of type 'javax.servlet.Filter' but was actually of type 'org.springframework.beans.factory.support.NullBean'异常的核心原因是测试类错误Mock了Spring Security核心配置类,导致容器无法正常生成springSecurityFilterChain关键Filter Bean。具体问题点:
- 无效Mock破坏安全配置:测试类Mock了
SecurityConfig和WebSecurityConfiguration,这两个是Spring Security的核心配置载体,Mock后容器无法构建完整安全过滤链,返回NullBean。 - 错误构建MockMvc:手动使用Mock的
WebApplicationContext构建MockMvc,而@WebMvcTest已自动配置并注入可用的MockMvc实例,重复构建导致上下文不完整。 - 权限不匹配:控制器方法用
@PreAuthorize("hasAuthority('CAN_VIEW_ALL_PLATFORM_MEMBERS')")验证权限,但测试中@WithMockUser仅指定角色PLATFORM_SUPER_ADMIN,未赋予对应权限,即便解决Bean问题,后续仍会权限验证失败。
解决方案
步骤1:清理无效MockBean
移除SecurityConfig、WebSecurityConfiguration、WebApplicationContext、CustomAuthorizationFilter这些不必要的MockBean,仅保留业务相关的UserService和Spring Security必需的UserDetailsService(因SecurityConfig依赖它)。
步骤2:移除手动构建MockMvc的代码
@WebMvcTest会自动配置并注入MockMvc实例,无需手动调用MockMvcBuilders构建,直接使用@Autowired的实例即可。
步骤3:修正@WithMockUser权限配置
给测试用户添加对应权限CAN_VIEW_ALL_PLATFORM_MEMBERS,确保与控制器的权限验证规则匹配。
修改后的测试类代码
package com.chama.chamaservice.user; import com.chama.chamaservice.user.UserService; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @WebMvcTest(controllers = UserController.class) class UserControllerTest { @MockBean private UserService userService; @MockBean private UserDetailsService userDetailsService; @Autowired private MockMvc mockMvc; @Test @WithMockUser(username = "254704760842", authorities = {"CAN_VIEW_ALL_PLATFORM_MEMBERS"}) @DisplayName("Should list all users GET: /api/users/") void shouldGetUsers() throws Exception { mockMvc.perform(get("/api/users")) .andExpect(status().is(200)) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)); } }
补充说明
@WebMvcTest会自动扫描指定控制器,配置Spring MVC核心组件,同时集成Spring Security测试支持,配合@WithMockUser可轻松模拟认证用户。- 若需自定义Spring Security测试配置,可使用
@TestConfiguration添加局部配置,而非Mock整个SecurityConfig。 - 需确保
UserService的Mock行为正确,比如用Mockito.when(userService.getUsers()).thenReturn(Collections.emptyList());模拟返回值,避免后续空指针问题。
内容的提问来源于stack exchange,提问作者Steve Otieno
相关产品推荐
相关产品推荐

