[Spring boot] Controller 테스트 시 발생하는 Security Config 에러 해결 방법

동재·2023년 7월 7일

CI|CD 구축을 위한 Test Case 작성 중 만난 문제이다.

통합테스트가 아닌 단위 테스트 작성을 위해 @WebMvcTest를 사용했는데 해당 어노테이션에 대해 제대로 알지 않고 사용해 해결에 오랜 시간이 걸렸다.


Security Config Error

"springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityConfig' defined in file "

📌원인

에러 로그를 확인해보면 보안 설정 파일(SecurityConfig)에 대한 Bean 생성 관련 문제가 있는 것으로 보인다.

하단의 SecurityConfig 클래스는 UserRepository에 의존한다. 따라서 UserRepository가 생성되지 않으면 SecurityConfig 파일 구성에 문제가 생겨 에러가 발생한다.

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter{

	private final UserRepository userRepository;

   ...
   ...
}

문제는 @WebMvcTest는 SecuriryConfig(WebSecurityConfigurerAdapter)는 스캔하지만 UserRepository(@Repository)는 스캔하지 않는 다는 점이다.

이유는 @WebMvcTest가 주로 Controller와 관련된 Bean들을 테스트하기 위한 목적으로 사용되기 때문이다.


@WebMvcTest Annotation 스캔 범위 정리

Scan O

  • @Controller,
  • @ControllerAdvice,
  • @JsonComponent,
  • Converter / GenericConverter,
  • Filter,
  • WebSecurityConfigurerAdapter,
  • WebMvcConfigurer,
  • HandlerMethodArgumentResolver

Scan X

  • @Servic
  • @Repository
  • @Component
  • @Bean

📗해결

excludeFilters 를 사용하여 WebSecurityConfigurerAdapter를 스캔 대상에서 제외하면 된다.

@WebMvcTest(value = CertController.class,
        excludeFilters = {
                @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = SecurityConfig.class),
        })
profile
Backend Developer

0개의 댓글