@WebMvcTest 是 Spring Boot 提供的一个测试注解,用于对 Spring MVC 控制器层进行单元测试。它会自动配置 MockMvc 实例,并加载指定的控制器类及其依赖的组件,但不会加载整个 Spring 应用上下文。
Spring Security 是一个强大的和高度可定制的身份验证和访问控制框架,用于保护基于 Spring 的应用程序。
@WebMvcTest 允许你专注于控制器层的测试,而不必加载整个应用上下文,从而提高测试速度。@WebMvcTest 主要有以下几种类型:
excludeFilters 和 includeFilters 属性,可以进一步自定义要加载或排除的组件。@MockBean 和 @SpyBean 注解结合使用,以模拟或监视其他 Spring Bean。当你需要测试以下场景时,可以使用 @WebMvcTest:
@WebMvcTest 无法加载 Spring Security 配置原因:@WebMvcTest 默认不会加载整个 Spring 应用上下文,因此可能无法找到 Spring Security 的配置。
解决方法:
@Import 注解显式导入 Spring Security 配置类。@ContextConfiguration 注解,并指定 Spring Security 配置类的位置。@WebMvcTest(controllers = MyController.class)
@Import(SecurityConfig.class) // 导入 Spring Security 配置类
public class MyControllerTest {
// ...
}或者
@WebMvcTest(controllers = MyController.class)
@ContextConfiguration(classes = {MyController.class, SecurityConfig.class})
public class MyControllerTest {
// ...
}原因:Spring Security 可能会拦截 MockMvc 发出的请求,并根据安全配置进行身份验证或授权。
解决方法:
@WithMockUser 注解,模拟一个已认证的用户。@WebMvcTest(controllers = MyController.class)
public class MyControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
@WithMockUser(username = "test", roles = "USER")
public void testMyController() throws Exception {
mockMvc.perform(get("/my-endpoint"))
.andExpect(status().isOk());
}
}或者在 Spring Security 配置中添加允许匿名访问的规则:
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/my-endpoint").permitAll() // 允许匿名访问 /my-endpoint
.anyRequest().authenticated();
}
}