" JUnit Error creating bean with name 'securityConfig' defined in file "
스프링 시큐리티를 추가하고 JUnit의 @WebMvcTest로 컨트롤러를 테스트할 때 아래와 같은 오류에 직면할 수 있다.
에러 메시지를 확인해보면 이는 SecurityConfig 에 대한 Bean 생성 관련 문제로 보인다.
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityConfig' defined in file ~
이 문제에 대한 해결책을 알아보자
다음은 @WebMvcTest어노테이션의 스캔 범위이다.
@Controller,
@ControllerAdvice,
@JsonComponent,
Converter / GenericConverter,
Filter,
WebSecurityConfigurerAdapter,
WebMvcConfigurer,
HandlerMethodArgumentResolver
읽어보면 알겠지만 @Service, @Repository, @Component Bean은 스캔하지 않는다.
문제는 여기서 발생한다.
SpringSecurity에 대한 내용은 위에 bold로 표현해놓았듯이 스캔대상에 포함된다.
하지만 대부분의 Spring Security Config에서는 아래 JwtUtil 같은 다른 Bean들에 대한 Dependency가 존재하게 된다.
해당 문제를 해결하기 위해서는 Controller Layer에 해당하는 내용에만 Test를 집중할 수 있도록 WebSecurityConfigurerAdapter를 스캔 대상에서 제외하고 @WithMockUser를 통해 Mock 인증 사용자를 생성한다.
@WebMvcTest에 excludeFilters 를 사용하여
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = SecurityConfig.class)
를 설정해주자.
@WebMvcTest(value = HealthCheck.class,
excludeFilters = {
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = SecurityConfig.class),
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = WebConfig.class),
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = JwtAuthenticationFilter.class)
})
'스터디' 카테고리의 다른 글
[SpringBoot] Swagger2 - java.lang.NumberFormatException: empty String (1) | 2022.09.10 |
---|---|
[SpringBoot] 빌드시 Command line is too long. 문제 해결법 (1) | 2022.07.01 |
테스트 주도 개발 TDD / BDD, 그리고 애자일 (1) | 2022.06.29 |
[객체지향 / 스프링] DI 와 IoC란 무엇인가 (1) | 2022.03.28 |
[객체지향] SOLID 원칙이란? (4) | 2022.03.28 |