@WebMvcTest 이란

- Spring Boot 테스트 어노테이션

- Sptring MVC 웹 계층의 테스트에 사용됨

- 서비스 계층, 데이터 액세스 계층, 외부 시스템과의 통신 등 다른 계층의 로직을 테스트하는 것이 아닌, 웹 계층의 로직만으로 테스트하려는 경우 사용

 

MockMvc 란

- HTTP 요청을 디스패처 서블릿에 전송하고 결과를 받아 테스트하는 데 사용됨

- API의 테스트 수행

- Spring MVC 구성요소를 사용하여 동작

- MockMvc 주입받아 사용할때 @WebMvcTest 어노테이션을 쓰지 않으면 "this.mockMvc" is null 오류 발생함

Cannot invoke "org.springframework.test.web.servlet.MockMvc.perform(org.springframework.test.web.servlet.RequestBuilder)" because "this.mockMvc" is null
java.lang.NullPointerException: Cannot invoke "org.springframework.test.web.servlet.MockMvc.perform(org.springframework.test.web.servlet.RequestBuilder)" because "this.mockMvc" is null

 

예제

@WebMvcTest
class PostControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    @DisplayName("/posts 요청시 Hello world를 출력한다.")
    void test() throws Exception {
        //expection
        mockMvc.perform(get("/posts"))
                .andExpect(status().isOk()) // 통신이 정상일때
                .andExpect(content().string("Hello World"))
                .andDo(print()); // 요청한 로그 보기 위해
    }
}

 

MockMvc.perform 메서드

- MockHttpServletRequestBuilder 객체를 인자로 받음

MockHttpServletRequestBuilder 객체는 API 호출을 나타내며, HTTP 메서드, URL, 요청 본문, 요청 해더 등을 설정 가능

 

 

 

 

+ Recent posts