본문 바로가기

spring boot

@WebMvcTest vs @AutoConfigureMockMvc

springframework의 @WebMvcTest 설명

 

원문:

Annotation that can be used for a Spring MVC test that focuses only on Spring MVC components.
Using this annotation will disable full auto-configuration and instead apply only configuration relevant to MVC tests (i.e. @Controller, @ControllerAdvice, @JsonComponent, Converter/GenericConverter, Filter, WebMvcConfigurer and HandlerMethodArgumentResolver beans but not @Component, @Service or @Repository beans).
By default, tests annotated with @WebMvcTest will also auto-configure Spring Security and MockMvc (include support for HtmlUnit WebClient and Selenium WebDriver). For more fine-grained control of MockMVC the @AutoConfigureMockMvc annotation can be used.
Typically @WebMvcTest is used in combination with @MockBean or @Import to create any collaborators required by your @Controller beans.
If you are looking to load your full application configuration and use MockMVC, you should consider @SpringBootTest combined with @AutoConfigureMockMvc rather than this annotation.
When using JUnit 4, this annotation should be used in combination with @RunWith(SpringRunner.class).

 

요약 : 

@WebMvcTest 어노테이션은 Spring MVC 컴포넌트에만 집중한 Spring MVC 테스트에 사용되며, 전체 구성을 다 읽어오지는 못한다. ( @Component, @Service or @Repository  빈은 읽어오지 못함)

그리고 Spring Security와 MockMvc는 자동으로 구성(auto-configure)하며, MockMVC의 fine-grained한 테스트에서는 @AutoConfigureMockMvc 어노테이션을 사용할 수 있다.

보통 테스트하려는 컨트롤러에서 요구하는 것들을 생성하기 위해 @MockMean이나 @Import 어노테이션과 같이 쓰인다.

만약 전체 어플리케이션 구성과 MockMVC을 읽어오려면 @SpringBootTest와 @AutoConfigureMockMvc를 사용하는 것이 좋다.

만약 JUnit4를 이용하고있다면 @RunWith(SpringRunner.class)와 함께 사용해야 한다.

 

결론 : 두 어노테이션 모두 Spring MVC 테스트에 사용되며, 좀 더 잘게 쪼개진 테스트를 하거나 어플리케이션 구성 전체를 읽어오려면 @AutoConfigureMockMvc + @SpringBootTest 를 사용하고, 아니면 @WebMvcTest 를 사용하여도 될 것 같다.

 

+) @WebMvcTest로 컨트롤러 테스트를 진행하려다가 Service단을 읽어오지 못해서 아래와 같이 @MockBean으로 서비스를 추가했다.

@WebMvcTest(controllers = MemberController.class)
//@AutoConfigureMockMvc
//@SpringBootTest
public class MemberControllerTest {
	
	@MockBean
	private MemberService memberService;
	
	@Autowired
	protected MockMvc mockMvc;
    ...

 

그랬더니 다음엔 아래의 에러가 발생했는데,

Cannot invoke "cohttp://m.tlog.backend.member.domain.Member.getId()" because "entity" is null

 

"entity"는 jpa를 이용해 데이터를 save한 뒤의 결과물을 담은 엔티티다. 위에 설명에서 말했듯이 @WebMvcTest는 전체 구성을 다 읽어오지는 못한다. 컨트롤러 관련 빈만 읽어온다. 따라서 @Service 의 빈도 읽어오지 못해 @MockBean을 사용해 임의의 빈을 생성하였으나, 그 뒤에 JPA 관련 빈도 읽어오지 못하기 때문에 저장하고, 그 결과를 전달하는 과정이 불가능하다. 해당 오류는  @AutoConfigureMockMvc + @SpringBootTest로 변경하여 해결했다.

(변경한 코드)

@AutoConfigureMockMvc
@SpringBootTest
public class MemberControllerTest {
	
	@Autowired
	protected MockMvc mockMvc;
	
    ...

 

따라서 컨트롤러단만 시행하는 단위테스트에는 @WebMvcTest가 적합하고, 통합테스트를 시행할 경우엔 @AutoConfigureMockMvc + @SpringBootTest를 이용하는 것이 적합하다.

 

 

참고 블로그: https://yeoonjae.tistory.com/entry/Spring-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-%ED%95%B4%EA%B2%B0

 

[Spring] @WebMvcTest 단위 테스트시 Bean 주입 에러 해결

들어가며.. 약..9시간..? 동안 삽질하게 했던 에러에 대해서 설명하려 합니다.. 9시간 넘게 헤매다가 너무나도 허무한 방법으로 해결했습니다 ^_ㅠ 발생한 오류 SpringBoot 에서 Controller 클래스를 테

yeoonjae.tistory.com

https://m.blog.naver.com/sosow0212/223076265261

 

[Spring] @Mock과 @MockBean의 차이점은 무엇일까?

혹시 글에 오류가 있으면 댓글로 피드백 부탁드립니다. 감사합니다 :) 안녕하세요. 이번에 우테코 미션을 ...

blog.naver.com

https://adjh54.tistory.com/347

 

[Java] Spring Boot MockMvc 이해하기 : 테스트 흐름 및 사용예제

해당 글에서는 MockMvc에 대해 이해하고 활용하는 방법에 대해 확인해 봅니다.   💡 [참고] 이전에 작성한 Test 관련 글들을 읽으시면 도움이 됩니다.분류링크JUnit 5 이론 및 구성 요소https://adjh54.

adjh54.tistory.com