TestCode
Mockito 사용하기
salmon16
2024. 7. 13. 23:32
개요
컨트롤러를 테스트할 때 서비스로직을 이용해야 할 때가 있다 이때 Mockito를 사용하자
방법
1. 사용할 서비스를 MockBean으로 등록한다.
@MockBean // 컨테이너에 mock으로 만든 객체를 넣어준다.
private ProductService productService;
2. 테스트 로직에서 mockBean의 동작 방법을 when을 사용해서 정한다.
List<ProductResponse> result = List.of();
when(productService.getSellingProducts()).thenReturn(result);
현재 테스트에서 productService의 getSellingProducts를 호출하면 result를 반환한다.
3. 테스트를 작성한다.
이때 객체를 Json으로 변환해 주기 위해 objectMapper.writeValueAsString을 사용한다.
@Autowired
private ObjectMapper objectMapper;
mockMvc.perform(post("/api/v1/products/new")
.content(objectMapper.writeValueAsString(request))
.contentType(MediaType.APPLICATION_JSON)
)
.andDo(print())
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.code").value("400"))
.andExpect(jsonPath("$.status").value("BAD_REQUEST"))
.andExpect(jsonPath("$.message").value("상품 타입은 필수입니다."))
.andExpect(jsonPath("$.data").isEmpty());
결과로 넘어온 Json을 확인하기 위해 jsonPath를 사용해서 Json의 값들을 테스트할 수 있다.