WebMvcTest, SpringBootTest

Byung Seon Kang·2022년 7월 26일

테스트

목록 보기
1/2

개론

  • 테스트코드를 작성하려는데 @WebMvcTest@SpringBootTest annotation이 있는데 이들의 차이가 뭔지 궁금해 알아보기로 했다.

@SpringBootTest

  • 주로 통합테스트를 할 때 사용되는 annotation.
  • @ContextConfiguration을 대체함.
  • 기본적으로 @SpringBootTest는 서버를 실행시키지 않는다.
    webEnvironment 속성을 사용해서 여러 설정이 가능함.
    • MOCK(Default) : Web ApplicationContext를 로드하고 가짜 web 환경을 제공. 이 annotation을 사용하면 임베디드 서버가 시작하지 않는다.
    • 이외에도 RANDOM_PORT, DEFINED_PORT, NONE이 있다.
    • RANDOM_PORTDEFINED_PORT의 경우 실제 웹 환경을 제공함. -> 다만 포트 번호가 랜덤이냐 아니냐의 차이.
  • 이 annotation을 사용하면 테스트에 사용할 ApplicationContext를 쉽게 생성하고 조작 가능.
  • 전체 빈 중에서 특정 빈을 선택해서 생성하거나, 특정 빈을 Mock으로 대체하거나 특정 Configuration을 선택하여 설정하고, 특정 프로퍼티 파일을 추가하는 등의 선택이 가능.
  • 테스트 웹 환경을 자동으로 설정해주는 기능이 있음.
  • classes라는 속성을 제공하는데, 해당 속성을 통해 빈을 생성할 클래스들을 지정할 수 있음.
  • Junit4까지는 @RunWith(SpringRunner.class)가 필요했지만 현재는 그렇지 않음.
    - Junit5부터 @RunWith가 아닌 Extension이라는 방법을 통해 테스트를 실행하는 방법을 커스터마이징함.
    • @ExtendWith(SpringExtension.class)을 사용하면 되지만, 이미 스프링 부트에서 제공하는 모든 테스트용 annotation에 meta annotation으로 적용되어 생략이 가능하다.

      If you are using JUnit 4, do not forget to also add @RunWith(SpringRunner.class) to your test, otherwise the annotations will be ignored. If you are using JUnit 5, there is no need to add the equivalent @ExtendWith(SpringExtension.class) as @SpringBootTest and the other @…​Test annotations are already annotated with it. - 공식문서

@WebMvcTest

  • Spring MVC component와 관련된 Spring MVC test에 사용되는 annotation.
  • full auto-configuration을 비활성화하고 MVC test에 연관된 configuration만 적용시킨다.
  • @SpringBootTest annotation을 올리는것보다 훨씬 가볍게 테스트를 진행할 수 있다.

적용되는 것들.

  • @Controller
  • @ControllerAdvice
  • @JsonComponent
  • Converter/GenericConverter
  • Filter
  • WebMvcConfigurer and HandlerMethodArgumentResolver beans

적용되지 않는 것들

  • @Component
  • @Service
  • @Repository beans

사용처

  • 주로 controller bean에서 @MockBean이나 @Import와 함께 사용된다고 한다.

    Typically @WebMvcTest is used in combination with @MockBean or @Import to create any collaborators required by your @Controller beans. - 공식문서

참고

SpringBootTest 공식문서
WebMvcTest 공식문서
meetup toast
SpringBoot공식문서
백기선님 글

profile
왜 필요한지 질문하기

0개의 댓글