logo头像

From zero to HERO

Spring Security 实战干货:单元测试

今天组里的新人迷茫的问我:哥,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就派上了用场。

@SneakyThrows
@Test
@WithUserDetails("felord")
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());
}

当我们执行单元测试时,将通过UserDetailsServiceloadUserByUsername方法查找用户名为felord的用户并加载到安全上下文中。

自定义注解

其实我们还可以模拟@WithMockUser

@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@WithSecurityContext(factory = WithMockUserSecurityContextFactory.class)
public @interface WithMockUser {

   String value() default "user";

   String username() default "";

   String[] roles() default { "USER" };

   String[] authorities() default {};

   String password() default "password";

   @AliasFor(annotation = WithSecurityContext.class)
   TestExecutionEvent setupBefore() default TestExecutionEvent.TEST_METHOD;

}

关键就在于@WithSecurityContext注解,我们只需要实现factory就行了,也就是:

public interface WithSecurityContextFactory<A extends Annotation> {

   SecurityContext createSecurityContext(A annotation);
}

这里如法炮制就行,没什么难度就不演示了。

总结

今天介绍了当你的应用中集成了Spring Security时如何单元测试,我们可以使用提供的模拟用户的注解,也可以模拟加载用户,甚至你可以根据自己的需要来定制化。其实如果你使用了JWT的话还有种野路子,你可以在Spring MVC Mock测试中加入对应的请求头或者参数,也能顺利进行。好了今天的分享就到这里,多多关注:码农小胖哥 分享更多的编程知识干货。

评论系统未开启,无法评论!