[성덕스토어] @WebMvcTest, @AuthenticationPrincipal 관련한 테스트 트러블 슈팅 (1부)

조성현·2023년 7월 20일

발단

다른 팀원분이 Controller Test Code를 작성하는 과정에서 Security-JwtUtil와 관련한 에러 메세지를 만나셨고, 헬프콜을 요청하셨다.


문제 1. @WebMvcTest 기반 Controller Test - [ Security 의존성주입 관련 이슈 ]

1-1 문제 분석

Caused by~ 부분을 자세히 살펴보니 NoSuchBeanDefinitionException관련 Ref이 원인이라는 점을 파악할 수 있었다.

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 
‘com.example.shoppingmallproject.common.security.jwt.JwtUtil’ available: expected at least 1 bean which qualifies as autowire candidate. 
Dependency annotations: {}

1-2 원인 파악

@WebMvcTest를 통해 테스트코드를 실행하는 경우 @Component, @Service or @Repository beans는 스캔 대상에서 제외됩니다.
(공식문서 Ref)

아래는 스프링 공식문서 발췌 
Annotation that can be used for a Spring MVC test that focuses only on Spring MVC components.
Using this annotation will disable full auto-configuration and instead apply only configuration relevant to MVC tests 
(i.e. @Controller, @ControllerAdvice, @JsonComponent, Converter/GenericConverter, Filter, WebMvcConfigurer and HandlerMethodArgumentResolver beans 
but not @Component, @Service or @Repository beans).

1-3 문제 해결

@MockBean을 활용하여 JwtUtil이 SecurityConfig에 의존성주입이 될 수 있게끔 하여 해결하였다.

  • 위와 같은 방법을 적용한 이유:
    - 해당 테스트의 목적이 Spring Security를 테스트함에 있지 않고, 아래와 같이 의존성주입 꼬리물기를 예방하기 위해
    @MockBean으로 JwtUtil을 주입함으로써 JwtUtiil에는 의존성주입을 하지 않게되며 흐름을 끊기 위함.

@MockBean 대신 @ComponentScan(관련Ref)을 통해 해결할 수 있지 않을까? 라는 의문이 들어 시도해본 결과 불필요한 의존성 주입이 꼬리에 꼬리를 물어 @WebMvcTest의 장점(가볍고 빠른 테스트)이 퇴색된다고 판단했다.


연달아 만난 문제...

열심히 세팅해둔 Test Code -> 눈앞에 펼쳐지는 NPE의 향연 ㅠ-ㅠ

이에 대한 해결스토리는 2부에 계속됩니다.

2부 글 링크

profile
맛있는 음식과 여행을 좋아하는 당당한 뚱땡이

1개의 댓글

comment-user-thumbnail
2023년 7월 20일

아주 유용한 정보네요!

답글 달기