본문 바로가기

BackEnd : Spring/SpringBoot

[Springboot] MockBean 테스트 코드 작성하기

@WebMvcTest
public class ProductControllerTest {
    @Autowired
    private MockMvc mockMvc;
    
    @MockBean
    ProductServiceImpl productService;
    
    @Test
    @DisplayName("MockMvc를 통한 Product 데이터 가져오기 테스트")
    void getProductTest() throws Exception {
        given(productService.getProduct(123L)).willReturn(
                new ProductResponseDto(123L,"pen",5000,2000)
        );
        
        String productId = "123";
        
        mockMvc.perform(
                get("/product?number="+productId))
                .andExpect(status().isOk())
                .andExpect(jsonPath(
                        "$.number").exists())
                .andExpect(jsonPath("$.name").exists())
                .andExpect(jsonPath("$.price").exists())
                .andExpect(jsonPath("$.stock").exists())
                .andDo(print());
        
        verify(productService).getProduct(123L);
    }
}

@WebMvcTest(테스트 대상 클래스.class)

웹에서 사용되는 요청과 응답에 대한 테스트 수행, 대상 클래스만 로드해 테스트를 수행

@SpringBootTest보다 가볍게 테스트하기 위해 수행

@MockBean

실제 빈 객체가 아닌 Mock(가짜) 객체를 생성해서 주입하는 역할

@MockBean이 선언된 객체는 실제 객체가 아니기 때문에 실제 행위를 수행하지 않음

해당 객체는 개발자가 Mockito의 given() 메서드를 통해 동작을 정의해야 함

  • given() : 이 객체에서 어떤 메서드가 호출되고 어떤 파라미터를 주입받는지 가정
  • willReturn() 메서드를 통해 어떤 결과를 리턴할 것인지 정의

MockMvc

컨트롤러의 api를 테스트하기 위해 사용된 객체

서블릿 컨테이너의 구동 없이 가상의 MVC 환경에서 모의 HTTP 서블릿을 요청하는 유틸리티 클래스

  • perform() : 서버로 url 요청을 보내는 것처럼 통신 테스트 코드를 작성해서 컨트롤러 테스트 가능
  • andExpect() : 결괏값 검증
  • andDo() : 요청과 응답의 전체 내용 확인
  • verify() : 지정된 메서드가 실행됐는지 검증