본문 바로가기
Spring

[Spring] @WebMvcTest 단위 테스트시 Bean 주입 에러 해결

by jaee_ 2021. 11. 21.

들어가며..

약..9시간..? 동안 삽질하게 했던 에러에 대해서 설명하려 합니다.. 9시간 넘게 헤매다가 너무나도 허무한 방법으로 해결했습니다 ^_ㅠ


발생한 오류

SpringBoot 에서 Controller 클래스를 테스트하는 코드를 작성하고 실행하니 다음과 같은 에러가 발생했습니다. 

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userController': Unsatisfied dependency expressed through field 'userService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.flab.doorrush.domain.user.service.UserService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:659) ~[spring-beans-5.3.12.jar:5.3.12]
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:639) ~[spring-beans-5.3.12.jar:5.3.12]
	at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:119) ~[spring-beans-5.3.12.jar:5.3.12]
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399) ~[spring-beans-5.3.12.jar:5.3.12]
...
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.flab.doorrush.domain.user.service.UserService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1790) ~[spring-beans-5.3.12.jar:5.3.12]
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1346) ~[spring-beans-5.3.12.jar:5.3.12]
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1300) ~[spring-beans-5.3.12.jar:5.3.12]
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:656) ~[spring-beans-5.3.12.jar:5.3.12]
	... 87 common frames omitted

 

 

에러는 'userController' 를 생성하는데 필요한 빈 'userService' 을 정의할 수 없다 는 에러였습니다. 

 

저의 프로젝트 구조는 다음과 같습니다.

Controller - Service(Interface) - ServiceImpl - Repository(Mapper)

 

Repository와 Service를 테스트 했을 땐 너무나도 정상적으로 돌아갔었습니다. 그런데 왜 정작 중요한 Controller 테스트 할 때 작동이 안되는지 모르겠습니다!!!!!!!

 


해결방법

 

구글링을 해보니 위 Unsatisfied dependency expressed through field ...~ 에러가 나타나는 이유는 대략적으로 4가지로 분류할 수 있었습니다. 

 

1. Annotation 을 제대로 붙이지 않았을 경우

  - 이 경우 Service와 Repository 어노테이션이 잘 붙어있는지 확인해보면 됩니다. Controller 클래스엔 @Controller 가 Service 구현 클래스엔 @Service , Dao 구현 클래스엔 @Reposiroty 가 잘 붙어있는지 확인해보세요. 

 

(저의 경우엔 아주 매우 정상적으로 붙어있었는데 안되었습니다.)

 

2. DB 설정을 잘못한 경우

  - DB 설정을 잘못해도 위의 오류가 발생한다고 합니다. 

 

3. Spring에 의해 스캔되지 않는 패키지에 정의한 경우

-  @ComponentScan에 의해 @Component (@Controller , @Service, @Repository...) 어노테이션이 붙은 객체들을 Bean으로 등록합니다. @ComponentSacn은 basepackage 를 기준으로 스캔하는데 이 package 기준 하위에 위치해야 대상으로 잡힌 경우에만 Bean으로 등록이 됩니다. 

 

4. @WebMvcTest는 웹과 관련된 빈만 주입이 되어 발생하는 경우

@WebMvcTest는 웹과 관련된 @Controller와 @ControllerAdvice 등과 같은 빈만 주입이 되고, @Service와 같은 빈은 주입되지 않는다고 합니다. Controller 생성 시 필요한 @Service가 있다면 이를 MockBean으로 주입시켜주면 됩니다. 

 

저의 경우엔 4번의 오류로 발생헀던 것이었습니다~!

이렇게 @WebMvcTest를 사용하여 Controller를 Test할때는 아래 내용들만 스캔하도록 제한 된다고 합니다. 

@Controller, @ControllerAdvice, @JsonComponent, 
Converter, GenericConverter, Filter, HandlerInterceptor,
WebMvcConfigurer, HandlerMethodArgumentResolver

 


 

 

참고한 사이트

https://velog.io/@gillog/SpringBoot-WebMvcTest-%EB%8B%A8%EC%9C%84-%ED%85%8C%EC%8A%A4%ED%8A%B8%EC%8B%9C-Bean-%EC%A3%BC%EC%9E%85-%EC%97%90%EB%9F%AC

'Spring' 카테고리의 다른 글

[Spring] JUnit5 사용하기  (0) 2021.12.05
[Spring] gradle build 실행 에러  (0) 2021.11.21
[Spring] RESTful API  (0) 2021.11.16
[Spring] PSA - 일관성 있는 서비스 추상화  (0) 2021.10.04
[Spring] AOP 에 대해서 (2)  (0) 2021.10.04

댓글