如何为标注@Configuration注解的Spring配置类编写JUnit测试用例
Spring Security 权限配置JUnit测试实现
第一步:引入所需测试依赖
在项目的测试依赖中添加Spring Security测试模块,以Maven为例:
<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>
第二步:调整原有配置(可选,按需修改)
你当前的配置仅声明了两个端点的公开权限,没有配置其余端点的默认规则。如果需要其余接口默认必须认证,建议先修改配置类:
@Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/actuator","/actuator/health").permitAll() .anyRequest().authenticated(); // 新增其余接口需认证的规则 } }
第三步:编写测试用例
使用MockMvc模拟请求验证权限规则,测试类代码如下:
import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.context.annotation.Import; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; // 替换为你项目中WebSecurityConfig的实际包路径 import com.yourpackage.config.WebSecurityConfig; @WebMvcTest @Import(WebSecurityConfig.class) public class WebSecurityConfigTest { @Autowired private MockMvc mockMvc; // 验证/actuator接口无需认证即可访问 @Test public void actuatorEndpointAllowAnonymousAccess() throws Exception { mockMvc.perform(get("/actuator")) .andExpect(status().isOk()); } // 验证/actuator/health接口无需认证即可访问 @Test public void actuatorHealthEndpointAllowAnonymousAccess() throws Exception { mockMvc.perform(get("/actuator/health")) .andExpect(status().isOk()); } // 验证其他接口未认证时无法访问 @Test public void otherEndpointsNeedAuthentication() throws Exception { mockMvc.perform(get("/test/any/other/path")) .andExpect(status().isUnauthorized()); } }
说明:即使
/test/any/other/path接口不存在也不影响测试,Spring Security的权限校验会在请求进入Controller层之前执行,只要权限规则生效就会返回401状态码。
内容的提问来源于stack exchange,提问作者Jyothsna
相关产品推荐
相关产品推荐

