순간을 기록으로

@SpringBootTest vs. @WebMvcTest 본문

Development/Spring

@SpringBootTest vs. @WebMvcTest

luminous13 2022. 9. 8. 00:59

상황

컨트롤러를 테스트하는 상황에서 어떤 경우에는 @SpringBootTest를 사용하고, 또 어떤 경우에는 @WebMvcTest를 사용하는 코드를 봤다. 어떤 기준으로 선택하는 건지 몰라 정리하게 되었다.

 

@SpringBootTest + @AutoConfigureMockMvc

 

  1. 특징
    • 프로젝트 안의 모든 빈을 등록하여 테스트를 한다
    • 단위 테스트와 같이 기능을 테스트할 때보다는 통합 테스트를 할 때 사용한다.
  2. 장점
    • 서버를 띄우고 모든 빈을 등록하기 때문에 다양한 테스트 중에서 가장 운영환경과 유사한 테스트다.
  3. 단점
    • 모든 빈을 등록하기 때문에 단위 테스트보다 시간이 더 걸린다.
  • @AutoConfigureMockMvc는 Mock 테스트를 해야 될 경우에 추가한다.
@SpringBootTest
@AutoConfigureMockMvc
class HelloControllerTest {

    @Autowired
    private MockMvc mvc;

    @DisplayName("hello가 리턴된다")
    @Test
    void test() throws Exception {
        String hello = "hello";

        mvc.perform(get("/hello"))
                .andExpect(status().isOk())
                .andExpect(content().string(hello));
    }
}

@WebMvcTest + @MockBean

  1. 특징
    • 컨트롤러(Web Layer)만을 테스트하고 싶을 경우에 사용한다.
    • Web Layer에 필요한 빈들만 등록하기 때문에 상대적으로 빠르고 가벼운 테스트를 할 수 있다.
      • @Controller, @ControllerAdivce 등은 사용할 수 있지만, @Service, @Component, @Repository는 사용할 수 없다.
  2. 장점
    • Web(스프링 MVC)에 집중한 테스트를 할 수 있다.
    • 필요한 빈들만 등록하기 때문에 @SpringBootTest보다 빠르고 가볍게 테스트할 수 있다.
    • 통합 테스트가 어려운 상황에서 Mock으로 테스트할 수 있다.
  3. 단점
    • 실제환경과 다른 Mock을 기반으로 하기 때문에, 실제 환경에서는 오류가 발생할 수 있다.
    • Mocking 메서드에 변경이 일어나면 수정을 해야한다.
@WebMvcTest(HelloController.class)
class HelloControllerTest {

    @Autowired
    private MockMvc mvc;
    
    @MockBean
    private TestService testService;

    @DisplayName("hello가 리턴된다")
    @Test
    void test() throws Exception {
        String hello = "hello";

        mvc.perform(get("/hello"))
                .andExpect(status().isOk())
                .andExpect(content().string(hello));
    }
}

참고

https://developer-pi.tistory.com/310

https://spring.io/guides/gs/testing-web/

 

Comments