Spring Boot中如何Mock带自定义注解的方法以绕过自定义OAuth鉴权?
你之前使用@WithMockUser不生效的核心原因是该注解仅适配Spring Security原生的权限校验逻辑,你们自研的@CustomAuthorizer对应的鉴权逻辑(通常是AOP切面、自定义拦截器、自定义Security Filter三种实现方式)没有读取SecurityContext中注入的模拟用户信息,所以不会生效。
可行绕过方案
方案1:Mock自定义鉴权的核心逻辑类(适配所有实现场景,优先级最高)
首先定位你们自研鉴权的核心执行类,直接Mock打桩跳过校验即可:
- 如果
@CustomAuthorizer是基于AOP切面实现:找到对应的切面类(比如命名为CustomAuthorizerAspect),在测试类中通过@MockBean注入该类:
@MockBean private CustomAuthorizerAspect customAuthorizerAspect; @Before public void mockAuth() { // 无返回值的切面方法用doNothing打桩 Mockito.doNothing().when(customAuthorizerAspect).check(any()); // 有布尔返回值的切面方法用下面的写法 // Mockito.when(customAuthorizerAspect.check(any())).thenReturn(true); }
- 如果是基于Token校验服务实现:找到校验Token/权限的服务类(比如
CustomOAuthTokenService),mock它的校验方法返回合法的权限结果:
@MockBean private CustomOAuthTokenService oAuthTokenService; @Before public void mockTokenValid() { Mockito.when(oAuthTokenService.validateToken(anyString())).thenReturn(true); Mockito.when(oAuthTokenService.checkPermission(any(), any())).thenReturn(true); }
方案2:测试环境覆盖Security配置,直接放行所有请求
如果你们的自定义鉴权是集成在Spring Security的Filter链中,可以写测试专用的Security配置,覆盖正式环境的配置:
@RunWith(SpringRunner.class) @SpringBootTest @Import(MainControllerMockTest.TestSecurityConfig.class) public class MainControllerMockTest { @TestConfiguration static class TestSecurityConfig { @Bean public SecurityFilterChain testSecurityFilterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests(auth -> auth.anyRequest().permitAll()) .csrf(csrf -> csrf.disable()); return http.build(); } } // 原有测试方法不变 @Test public void testApi() throws Exception { // ...原有测试逻辑 } }
方案3:使用@WebMvcTest做轻量Controller测试
如果仅需要测试Controller的参数校验、业务逻辑调用、返回值封装,不需要加载全Spring上下文,可以用@WebMvcTest仅加载指定的Controller,自动排除所有鉴权相关的自动配置:
@RunWith(SpringRunner.class) @WebMvcTest(MainController.class) public class MainControllerMockTest { @Autowired private MockMvc mockMvc; // Mock Controller依赖的业务服务Bean @MockBean private YourBizService yourBizService; @Test public void testApi() throws Exception { // 原有测试逻辑,不需要传Authorization头也能正常调用 } }
内容的提问来源于stack exchange,提问作者prab2112
相关产品推荐
相关产品推荐

