[Util] Controller 단위 테스트 (@WebMvcTest, MockMvc)

@WebMvcTest

Application Context 를 완전하게 실행시키지 않고 (Start) layer 만 테스트 하고 싶을때

@WebMvcTest 를 사용하는것을 고려한다.

RestApi 사용할때 특히 좋다.

 

 

MockMvc

애플리케이션을 배포하지 않고도, 서버의 MVC 동작을 테스트 할 수 있는 라이브러리이다.

주로 Controller 레이어 단위테스트에 많이 사용된다. 

 

@WebMvcTest
class PostControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    @DisplayName("/posts 요청시 Hello World 를 출력한다.")
    void Post() throws Exception {

        // expected
        mockMvc.perform(MockMvcRequestBuilders.post("/posts")
                        .contentType(MediaType.APPLICATION_JSON_VALUE)
                        .content("{\"title\":\"제목\",\"content\":\"내용\"}")
                )
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.content().string("Hello World"))
                .andDo(MockMvcResultHandlers.print()); // 콘솔창 직히기
    }
}

 

 

 

 

** Controller 부분에 Log 를 찍으면 Log 값도 같이찍힌다 **

@Slf4j
@RestController // ResponseBody + Controller = RestController
public class PostController {

    @PostMapping("/posts")
    public String get(@RequestBody PostCreate create) {
        log.info("create = {}" , create.toString());
        return "Hello World";
    }

}