SpringBoot集成JUnit5测试-SpringSecurity中的单元测试-《Java笔记》

admin 2025-10-19 05:38:13 编程 来源:ZONE.CI 全球网 0 阅读模式

Java Spring Security

Spring Security 测试环境

要想在单元测试中使用Spring Security,需要在Spring Boot项目中集成:

  1. <dependency>
  2. <groupId>org.springframework.security</groupId>
  3. <artifactId>spring-security-test</artifactId>
  4. <scope>test</scope>
  5. </dependency>

这样测试的上下文配置就能和Spring Security结合起来了。

Spring Security 测试

所有的测试都是在Spring Boot Test下进行的,也就是@SpringBootTest注解的支持下。

@WithMockUser

@WithMockUser注解可以在Spring Security安全上下文中模拟一个默认名称为user,默认密码为password,默认角色为USER的用户。当测试方法使用了该注解后,就能通过:

  1. Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

获取该模拟用户的信息,也就“假装”当前登录了用户user。当然也可以根据需要来自定义用户名、密码、角色:

  1. @SneakyThrows
  2. @Test
  3. @WithMockUser(username = "fcant",password = "fcant.cn",roles = {"ADMIN"})
  4. void updatePassword() {
  5. mockMvc.perform(post("/user/update/password")
  6. .contentType(MediaType.APPLICATION_JSON)
  7. .content("{\n" +
  8. " \"newPassword\": \"12345\",\n" +
  9. " \"oldPassword\": \"12345\"\n" +
  10. "}"))
  11. .andExpect(ResultMatcher.matchAll(status().isOk()))
  12. .andDo(print());
  13. }

当然可以将@WithMockUser标记到整个测试类上,这样每个测试都将使用指定该用户。

@WithAnonymousUser

@WithAnonymousUser是用来模拟一种特殊的用户,也被叫做匿名用户。如果有测试匿名用户的需要,可以直接使用该注解。其实等同于@WithMockUser(roles = {"ANONYMOUS"}),也等同于@WithMockUser(authorities = {"ROLE_ANONYMOUS"})

@WithUserDetails

虽然@WithMockUser是一种非常方便的方式,但可能并非在所有情况下都凑效。有时候魔改了一些东西使得安全上下文的验证机制发生了改变,比如定制了UserDetails,这一类注解就不好用了。但是通过UserDetailsService加载的用户往往还是可靠的。于是@WithUserDetails就派上了用场。

  1. @SneakyThrows
  2. @Test
  3. @WithUserDetails("fcant")
  4. void updatePassword() {
  5. mockMvc.perform(post("/user/update/password")
  6. .contentType(MediaType.APPLICATION_JSON)
  7. .content("{\n" +
  8. " \"newPassword\": \"12345\",\n" +
  9. " \"oldPassword\": \"12345\"\n" +
  10. "}"))
  11. .andExpect(ResultMatcher.matchAll(status().isOk()))
  12. .andDo(print());
  13. }

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

自定义注解

其实还可以模拟@WithMockUser

  1. @Target({ ElementType.METHOD, ElementType.TYPE })
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Inherited
  4. @Documented
  5. @WithSecurityContext(factory = WithMockUserSecurityContextFactory.class)
  6. public @interface WithMockUser {
  7. String value() default "user";
  8. String username() default "";
  9. String[] roles() default { "USER" };
  10. String[] authorities() default {};
  11. String password() default "password";
  12. @AliasFor(annotation = WithSecurityContext.class)
  13. TestExecutionEvent setupBefore() default TestExecutionEvent.TEST_METHOD;
  14. }

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

  1. public interface WithSecurityContextFactory<A extends Annotation> {
  2. SecurityContext createSecurityContext(A annotation);
  3. }

这里如法炮制就行。

总结

当项目中集成了Spring Security时如何单元测试,可以使用提供的模拟用户的注解,也可以模拟加载用户,甚至可以根据自己的需要来定制化。其实如果使用了JWT的话,可以在Spring MVC Mock测试中加入对应的请求头或者参数,也能顺利进行。

以太坊cppgolang区别 编程

以太坊cppgolang区别

以太坊是一种去中心化的开源平台,它采用智能合约技术,旨在构建和运行不受干扰的分布式应用程序。作为目前最受欢迎的区块链平台之一,以太坊提供了多种编程语言的支持,其
progolang 编程

progolang

Go语言(Golang)是由Google开发的一门静态类型编程语言。作为一名专业的Golang开发者,我深知这门语言的优势和特点。在本文中,我将介绍Golang
golangn个发送者 编程

golangn个发送者

Golang是一种开源的编程语言,由Google团队开发,旨在提高程序的并发性和简化软件开发过程。在Go语言中,有时需要向多个接收者发送信息。本文将介绍如何在G
golang技能图谱 编程

golang技能图谱

从互联网行业的快速发展到人工智能技术的日益成熟,各种编程语言也应运而生。而在这众多的编程语言中,Golang(即Go)作为一门强大且高效的开发语言备受关注。Go
评论:0   参与:  13