Web/Spring
[Spring] SpringBoot : Bean 생성 오류
땀두
2022. 4. 11. 18:34
스프링부트 테스트코드를 아래와 같이 작성하여 실행을 해보았는데 에러가 발생하였다.
@SpringBootTest
public class MainControllerTest {
@Autowired
private MockMvc mvc;
@Test
public void mainTest() throws Exception {
String main = "main";
mvc.perform(get("/main"))
.andExpect(status().isOk())
.andExpect(content().string(main));
}
}
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'springboot.web.MainControllerTest': Unsatisfied dependency expressed through field 'mvc'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.test.web.servlet.MockMvc' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} |
이 문제는 책에서 사용하던 RunWith 어노테이션과 WebMvcTest를 SpringBootTest 하나로 퉁쳐도 될 것이라는 짧은 생각에 생긴 오류였다.
그래서 @WebMvcTest 어노테이션을 추가해주면 될 것이라고 생각했지만 이는 각자 서로의 MockMvc를 mocking하기 때문에 충돌이 발생해서 @SpringBootTest와 같이 사용될 수 없다.
해결 방법은 @WebMvcTest 어노테이션만을 사용하거나, @SpringBootTest 어노테이션과 @AutoConfigureMockMvc 어노테이션을 함께 사용하면 문제 해결이 가능하다.
스프링 부트와 AWS로 혼자 구현하는 웹 서비스
https://pinokio0702.tistory.com/162?category=411278