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

Spring Security环境下如何用@WebMvcTest测试控制器?

解决@WebMvcTest测试Spring Security保护的Web层问题

针对你遇到的@WebMvcTest因Security配置依赖缺失导致启动失败的问题,有以下几种可行方案:

方案1:Mock Security配置的直接依赖

最直接的方式是用@MockBean模拟TokenAuthenticationProvider和UsernamePasswordAuthenticationProvider,让Spring能初始化WebSecurityConfig,无需加载真实的Provider实现及其依赖的UserService、TokenService等Bean。

示例测试代码:

@WebMvcTest(YourTargetController.class)
class YourControllerTest {

    @Autowired
    private MockMvc mockMvc;

    // 模拟SecurityConfig依赖的两个认证Provider
    @MockBean
    private TokenAuthenticationProvider tokenProvider;

    @MockBean
    private UsernamePasswordAuthenticationProvider usernamePasswordAuthenticationProvider;

    // 提前设置Mock的认证行为(按需配置)
    @BeforeEach
    void setUp() {
        // 模拟Token认证通过,返回已授权的Authentication对象
        Authentication authenticatedUser = new UsernamePasswordAuthenticationToken(
                "test-user",
                null,
                Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))
        );
        when(tokenProvider.authenticate(any(Authentication.class)))
                .thenReturn(authenticatedUser);
    }

    @Test
    void testSecuredApi_WithValidToken_ReturnsOk() throws Exception {
        mockMvc.perform(get("/api/secured")
                        .header("Authorization", "Bearer dummy-token"))
                .andExpect(status().isOk());
    }
}

这种方案适合仅测试控制器的业务逻辑、请求映射,无需验证真实认证流程的场景。

方案2:导入Security配置+Mock底层依赖

如果需要验证Security的配置规则(比如路径权限、过滤器顺序),可以通过@Import导入WebSecurityConfig,同时用@MockBean模拟Provider依赖的底层服务(如UserService、TokenService),让整个Security配置能正常初始化。

示例测试代码:

@WebMvcTest(YourTargetController.class)
@Import(WebSecurityConfig.class)
class YourControllerSecurityTest {

    @Autowired
    private MockMvc mockMvc;

    // Mock Provider依赖的底层服务
    @MockBean
    private UserService userService;

    @MockBean
    private TokenService tokenService;

    // 按需设置UserService/TokenService的Mock行为
    @BeforeEach
    void setUp() {
        when(userService.findByUsername(anyString()))
                .thenReturn(new User("test-user", "encoded-pass", Collections.singletonList(new SimpleGrantedAuthority("ROLE_ADMIN"))));
    }

    @Test
    void testAdminApi_WithAdminUser_ReturnsOk() throws Exception {
        mockMvc.perform(get("/api/admin")
                        .with(user("test-user").roles("ADMIN")))
                .andExpect(status().isOk());
    }
}

方案3:使用Spring Security测试注解模拟认证

如果仅需验证接口的权限控制逻辑,可结合Spring Security提供的@WithMockUser、@WithUserDetails等注解模拟已认证用户,同时配合@MockBean解决SecurityConfig的依赖问题。

示例:

@WebMvcTest(YourTargetController.class)
class YourControllerPermissionTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private TokenAuthenticationProvider tokenProvider;

    @MockBean
    private UsernamePasswordAuthenticationProvider usernamePasswordAuthenticationProvider;

    @Test
    @WithMockUser(username = "test-user", roles = "USER")
    void testUserApi_WithUserRole_ReturnsOk() throws Exception {
        mockMvc.perform(get("/api/user"))
                .andExpect(status().isOk());
    }

    @Test
    @WithMockUser(username = "guest", roles = "GUEST")
    void testUserApi_WithGuestRole_ReturnsForbidden() throws Exception {
        mockMvc.perform(get("/api/user"))
                .andExpect(status().isForbidden());
    }
}

方案4:用@SpringBootTest配合@AutoConfigureMockMvc

如果需要测试完整的认证流程(如真实的Token解析、用户信息校验),不想Mock大量Bean,可以放弃@WebMvcTest,改用@SpringBootTest加载完整Spring上下文,配合@AutoConfigureMockMvc测试Web层。

示例:

@SpringBootTest
@AutoConfigureMockMvc
class YourControllerFullFlowTest {

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private TokenService tokenService;

    @Test
    void testSecuredApi_WithRealToken_ReturnsOk() throws Exception {
        // 生成真实有效的Token
        String validToken = tokenService.generateToken("test-user");

        mockMvc.perform(get("/api/secured")
                        .header("Authorization", "Bearer " + validToken))
                .andExpect(status().isOk());
    }
}

这种方案的缺点是测试启动速度较慢,适合需要端到端验证Web层+认证流程的场景。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 20:24:23