오류 내용

java.lang.IllegalStateException: Failed to load ApplicationContext
...
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'io.github.service.FooService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1662)
...

보통 이 오류는 굉장히 많은 경우에 있어서 자주 보게 되는 오류이므로 'Failed to load ApplicationContext' 이 메세지보다는 아래에서 나타나는 원인 메시지를 봐야 한다.

따라서 위의 메시지보단 아래의 오류를 봐야 한다.

No qualifying bean of type 'io.github.service.FooService' available: expected at least 1 bean which qualifies as autowire candidate.

 

해결 방안

@WebMvcTest 을 사용하면서 @MockBean 을 걸어주지 않은 것이 있으면 해당 오류가 발생한다.

따라서 @MockBean 을 사용하여 오류 내용 안에 나타나는 Bean 을 추가하면 된다.

 

비록, @SpringBootTest 을 사용하면 바로 해결되긴 하지만 통합 테스트가 되어 버리고, 테스트를 할 때 오랜 시간이 걸리기 때문에 간단한 단위 테스트를 작성하려는 경우에는 이는 좋은 해결 방법이 아니다.

 

참고로 @WebMvcTest 는 @WebMvcTest 에는 JPA 에 대한 테스트 설정이 빠져있어서 만약 @MockBean 을 걸어준 것 중에 JPA 를 사용한 Repository 가 있으면 위와 같은 오류를 겪을 수도 있다.

그럴 때는 아래와 같은 Annotation 을 추가하면 된다.

@MockBean(JpaMetamodelMappingContext.class)

그러면 자동으로 JPA 에 대한 Context 를 넣어주면서 해결이 된다.