[Springboot] @WebMvcTest를 활용한 단위 테스트시 Bean 주입 에러

유아 Yooa·2023년 5월 25일
0

미숙한 삽질

목록 보기
4/5
post-thumbnail

JUnit4 @WebMvcTest로 Controller 테스트 코드를 작성 중에 에러가 발생했다.

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'forecastController' defined in file [/Users/jeongmin/spring_workspace/open-api-test/demo/build/classes/java/main/com/example/demo/forecast/controller/ForecastController.class]: Unsatisfied dependency expressed through constructor parameter 0: No qualifying bean of type 'com.example.demo.forecast.service.ForecastService' 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 'com.example.demo.forecast.service.ForecastService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

Service bean이 주입되지 않아서 발생한 것 같은 오류였고 실제 실행에서는 오류없이 돌아가는 것을 발견했다.

테스트 코드 작성에 미숙한 탓에 bean 주입에서 문제가 있는 듯 하다.

찾아본 결과, @WebMvcTest는 웹과 관련된 bean(e.g. @Controller)만 주입되고 @Component는 주입되지 않는다고.

그래서 @Service bean이 주입되지 않아 Controller 생성에서 오류가 발생했다.

@MockBean
private ForecastService forecastService;

@MockBean을 통해 주입해주었더니 해결했다.


ref
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

profile
기록이 주는 즐거움

0개의 댓글