Spring

@WebMvcTest에서 Security config class 제외시키기

leeheefull 2022. 3. 10. 21:42

Description

 

  • Junit 5 환경에서 스프링 슬라이스 테스트를 위해서 컨트롤러 테스트를 진행하던 중 JWT 토큰 관련해서 에러가 발생했습니다.
  • 테스트하려고 하는 URL이 시큐리티에서 허락을 안해주고 있기 때문에 인증을 받아야 테스트를 할 수 있습니다.
  • 독립적인 테스트를 하는게 중요한 것이기 때문에 시큐리티까지 해줄 필요는 없다고 생각했습니다.
  • 그래서, @WebMvcTest에 대한 Spring Security config 클래스를 비활성화시켜주어서 해결했습니다.

Error message

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of constructor in kr.ac.hs.selab.common.config.SecurityConfig required a bean of type 'kr.ac.hs.selab.auth.jwt.JwtTokenProvider' that could not be found.

Action:

Consider defining a bean of type 'kr.ac.hs.selab.auth.jwt.JwtTokenProvider' in your configuration.

ERROR o.s.test.context.TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@6b5966e1] to prepare test instance [kr.ac.hs.selab.board.presentation.BoardControllerTest@f017dd0]
java.lang.IllegalStateException: Failed to load ApplicationContext
...
...
...
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityConfig' defined in file [/Users/leeheechan/Documents/workspace/selab-blog-api/out/production/classes/kr/ac/hs/selab/common/config/SecurityConfig.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'kr.ac.hs.selab.auth.jwt.JwtTokenProvider' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
...
...
...
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'kr.ac.hs.selab.auth.jwt.JwtTokenProvider' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
...
...
...

 

Solution

Conclusion

Before

https://user-images.githubusercontent.com/58816862/157664456-963cee88-591a-45e6-9099-bd5249e431bb.png

After

https://user-images.githubusercontent.com/58816862/157664565-7e53e91a-0ca3-495a-b0aa-be54e0bd3df3.png