Spring Boot 6 REST应用测试添加安全配置时出现UnsatisfiedDependencyException的原因
问题原因
这个异常是因为Spring Security 6在处理authorizeHttpRequests配置时,依赖Spring MVC的路径匹配组件,但测试环境中该组件未正确初始化,导致mvcPatterns变量为空。
解决方案
方案一:显式指定请求匹配器
修改SecurityFilterChain配置,用requestMatchers明确指定需要拦截的路径,避免依赖隐式的MVC路径匹配:
@Configuration @EnableWebSecurity public class WebSecurityConfig { @Bean SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests((authz) -> authz .requestMatchers("/**").authenticated() // 显式匹配所有路径 ) .httpBasic(withDefaults()); return http.build(); } }
方案二:确保测试类加载完整Web上下文
- 如果是集成测试,使用
@SpringBootTest并指定Web环境,让Spring Boot自动加载MVC相关配置:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class YourIntegrationTest { // 测试代码逻辑 }
- 如果是Web层单元测试(如使用
@WebMvcTest),需结合Spring Security测试支持,并确保加载必要配置:
@WebMvcTest(YourTargetController.class) @Import(WebSecurityConfig.class) class YourControllerTest { @Autowired private MockMvc mockMvc; // 测试代码,可使用@WithMockUser模拟认证用户 }
方案三:检查测试依赖完整性
确保项目测试依赖包含Spring Boot Starter Test和Spring Security Test,以保证测试环境组件齐全:
Maven示例
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> </dependencies>
Gradle示例
dependencies { testImplementation 'org.springframework.boot:spring-boot-starter-test' testImplementation 'org.springframework.security:spring-security-test' }
内容的提问来源于stack exchange,提问作者AlexSC
相关产品推荐
相关产品推荐

