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

@SecurityTestExecutionListeners无法配置SecurityContext,测试获取认证信息失败

问题原因与解决方案

这不是Bug,是你的测试类缺少了Spring测试框架的基础配置支持。

@SecurityTestExecutionListeners注解的作用是配置Spring Security的测试监听器,但它必须依托Spring TestContext框架才能生效。你的测试类没有启用Spring的测试扩展,导致这个注解的配置根本没被加载,@WithMockUser自然无法把模拟用户注入到SecurityContext里。

而@SpringBootTest能成功运行,是因为它默认自带了@ExtendWith(SpringExtension.class),自动启用了Spring测试框架,同时也引入了Spring Security所需的测试监听器,所以@WithMockUser能正常工作。

解决办法

方法一:添加Spring测试扩展注解

给测试类加上@ExtendWith(SpringExtension.class),配合@SecurityTestExecutionListeners使用即可:

@ExtendWith(SpringExtension.class)
@SecurityTestExecutionListeners
class SecurityServiceTest {

    @Test
    @WithMockUser(username = "foo")
    void should_find_user() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        assertThat(authentication).isNotNull();
    }
}

方法二:直接使用@TestExecutionListeners指定监听器

@SecurityTestExecutionListeners本质是一个快捷注解,等价于@TestExecutionListeners(listeners = SpringSecurityTestExecutionListener.class),你也可以直接用这个写法替代:

@ExtendWith(SpringExtension.class)
@TestExecutionListeners(listeners = SpringSecurityTestExecutionListener.class)
class SecurityServiceTest {

    // 测试方法不变
}

如果你的测试不需要完整的Spring Boot上下文,第一种方法就足够满足需求;如果需要加载特定的Spring配置,也可以搭配@ContextConfiguration注解一起使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 13:33:05