HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
🤩
개발
/
Spring
Spring
/
🎽
Spring Security Test
🎽

Spring Security Test

 

@WithMockUser( 공식문서 )

@Test @WithMockUser public void getMessageWithMockUser() { String message = messageService.getMessage(); ... }
  • The user with the username "user" does not have to exist since we are mocking the user
  • The Authentication that is populated in the SecurityContext is of type UsernamePasswordAuthenticationToken
  • The principal on the Authentication is Spring Security’s User object
  • The User will have the username of "user", the password "password", and a single GrantedAuthority named "ROLE_USER" is used.
 

@WithSecurityContext

  • WithMockCustomUserSecurityContextFactory에서 WithMockCustomUser를 받아서 Authentication을 생성하고 SecurityContext에 설정하는 것 까지 진행해줌 → 완전한 Customizing이 가능함
@Retention(RetentionPolicy.RUNTIME) @WithSecurityContext(factory = WithMockCustomUserSecurityContextFactory.class) public @interface WithMockCustomUser { String username() default "testUser"; String password() default "12345678"; }
public class WithMockCustomUserSecurityContextFactory implements WithSecurityContextFactory<WithMockCustomUser> { @Override public SecurityContext createSecurityContext(WithMockCustomUser customUser) { SecurityContext context = SecurityContextHolder.createEmptyContext(); Long principal = 1L; // userId; Authentication auth = new UsernamePasswordAuthenticationToken(principal, customUser.password(), AuthorityUtils.NO_AUTHORITIES); context.setAuthentication(auth); return context; } }