HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
🧑🏻‍💻
박진형
/
🌲
Resume - 형욱 (1)
/
🖼️
프로젝트 관리 (1)
/
🍯
꿀기술문서
/
🎳
테스트 코드 - 토큰 정보 설정
🎳

테스트 코드 - 토큰 정보 설정

태그
Test
Security
작성자
작성 날짜
Nov 19, 2022 09:26 AM
컨트롤러에서 Authentication 정보를 사용하는 경우!✨ 설정은 이제 매우 간단해집니다.끗…?
 
🏆
부족한 부분이 있다면 누가 내용 보충좀 해주세요 🤟

컨트롤러에서 Authentication 정보를 사용하는 경우!

notion image
조금 억지스러운 예제이긴 하지만… 😓  컨트롤러에서 위와 같이 @AuthenticationPrincipal를 사용해서 토큰 정보를 사용한다고 가정해보겠습니다.
 
이 경우에 테스트 코드에서 그냥 테스트를 하게 되면 아래와 같은 오류를 만나게 됩니다. 이유는 토큰 정보를 찾을 수가 없기 때문입니다. 😱
notion image
 
그래서 테스트 하기 위해서는 토큰 정보를 설정해줘야 합니다. 이전 인스타뀨램에서는 아래와 같이 테스트 클래스에서 별도의 메서드를 정의해줘야 했습니다. 🫠
notion image
 
✨✨ 이를 조금 더 손쉽게 사용할 수 있도록 어노테이션 클래스를 생성했습니다.
notion image
public class WithMockJwtAuthenticationSecurityContextFactory implements WithSecurityContextFactory<WithMockJwtAuthentication> { @Override public SecurityContext createSecurityContext(WithMockJwtAuthentication annotation) { SecurityContext context = SecurityContextHolder.createEmptyContext(); JwtAuthenticationToken authentication = new JwtAuthenticationToken( new JwtAuthentication(annotation.token(), annotation.id(), annotation.username()), null, createAuthorityList(annotation.role()) ); context.setAuthentication(authentication); return context; } }
@Retention(RetentionPolicy.RUNTIME) @WithSecurityContext(factory = WithMockJwtAuthenticationSecurityContextFactory.class) public @interface WithMockJwtAuthentication { String token() default "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxIiwicm9sZXMiOlsiVVNFUiJdLCJpc3MiOiJzZmFtIiwiZXhwIjoxNjU4NTkyNTYyLCJpYXQiOjE2NTg1OTI1MzIsInVzZXJJZCI6MSwidXNlcm5hbWUiOiJ0ZXN0MDAifQ.FDkOUzhLvKOYFmjOxRtF-dRDSO2BkoplJTMIyhp0c0ajxOLeZbKuekSyySnCnjVvv_f0Qx8T7a3ZS2OlaSGiDQ"; long id() default 1L; String username() default "test00"; String role() default "USER"; }
토큰 설정에 필요한 필드들과 함께 Default 값들을 설정했습니다. 이를 사용하신다면 해당 값으로 토큰 정보가 설정되기 때문에 해당 필드의 값으로 테스트 해주시면 됩니다.
  • 토큰은 application-mem.yml의 테스트 키로 만든 값입니다. (배포 환경의 실제 키로 만든 토큰을 넣는건 위험할 수 있겠죠? 🫠 )
    • notion image
🙅‍♂️
해당 클래스는 공통적으로 사용되는 값이기 때문에 Default값을 변경은 팀원들 검토 후에 해주세요.
 

✨ 설정은 이제 매우 간단해집니다.

어노테이션만 사용해주시면 이제 토큰 정보가 위의 클래스에서 설정된 정보로 사용됩니다.
notion image
  • 이제 테스트를 다시 해보면 상큼하게 성공하게 됩니다.
    • notion image
 

끗…?

정보가 더 필요하다면 아래의 블로그가 참고가 될것 같습니다. 👍
Spring Security가 적용된 곳을 효율적으로 테스트하자.
Spring Security와 관련된 기능을 테스트하다보면 인증 정보를 미리 주입해야 하는 경우가 종종 발생한다. 기본적으로 생각할 수 있는 가장 간단한 방법은 테스트 전에 SecurityContext에 직접 Authentication을 주입하는 것이다. 다만 이렇게 할 경우, 인증 정보를 필요로 하는 메서드를 테스트할 때 항상 SecurityContext에 Authentication을 주입해야 하는 번거로움이 생길 수 있으며, setUp을 통해 관리를 한다고 해도 메서드에서 요구되는 권한 설정이 바뀔 경우, SecurityContext를 비우고 다시 원하는 정보로 채워야하는 번거로움이 생기게 된다.
Spring Security가 적용된 곳을 효율적으로 테스트하자.
https://tecoble.techcourse.co.kr/post/2020-09-30-spring-security-test/
Spring Security가 적용된 곳을 효율적으로 테스트하자.