今天组里的新人迷茫的问我:哥,Spring Security弄的我单元测试跑不起来,总是401,你看看咋解决。没问题,有写单元测试的觉悟,写的代码质量肯定有保证,对代码质量重视的态度,这种忙一定要帮!
Spring Security 测试环境
要想在单元测试中使用Spring Security,你需要在Spring Boot项目中集成:
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
这样测试的上下文配置就能和Spring Security结合起来了,接下来教你几招。
Spring Security 测试
所有的测试都是在Spring Boot Test下进行的,也就是@SpringBootTest注解的支持下。
@WithMockUser
@WithMockUser注解可以帮我们在Spring Security安全上下文中模拟一个默认名称为user,默认密码为password,默认角色为USER的用户。当你的测试方法使用了该注解后,你就能通过:
Authentication authentication = SecurityContextHolder.getContext()
.getAuthentication();
获取该模拟用户的信息,也就“假装”当前登录了用户user。当然你也可以根据需要来自定义用户名、密码、角色:
@SneakyThrows
@Test
@WithMockUser(username = "felord",password = "felord.cn",roles = {"ADMIN"})
void updatePassword() {
mockMvc.perform(post("/user/update/password")
.contentType(MediaType.APPLICATION_JSON)
.content("{\n" +
" \"newPassword\": \"12345\",\n" +
" \"oldPassword\": \"12345\"\n" +
"}"))
.andExpect(ResultMatcher.matchAll(status().isOk()))
.andDo(print());
}
当然你可以将@WithMockUser标记到整个测试类上,这样每个测试都将使用指定该用户。
@WithAnonymousUser
@WithAnonymousUser是用来模拟一种特殊的用户,也被叫做匿名用户。如果有测试匿名用户的需要,可以直接使用该注解。其实等同于@WithMockUser(roles = {"ANONYMOUS"}),也等同于@WithMockUser(authorities = {"ROLE_ANONYMOUS"}),细心的你应该能看出来差别。
@WithUserDetails
虽然@WithMockUser是一种非常方便的方式,但可能并非在所有情况下都凑效。有时候你魔改了一些东西使得安全上下文的验证机制发生了改变,比如你定制了UserDetails,这一类注解就不好用了。但是通过UserDetailsService 加载的用户往往还是可靠的。于是@WithUserDetails就派上了用场。