강의에서 api controller test 에 mockMvc를 활용해서 결과에 대한 검증을 status 정도로만 하고 있는데
jsonPath
를 활용해서 응답받은 json의 결과를 검증할 수 있습니다.$로 시작하는 json path 표현식으로 검증하고자 하는 value값을 선택하여 검증할 수 있습니다.
활용예시
- jsonPath안의 패턴 매칭 사용방법 참고 :
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; @WebMvcTest class VoucherRestControllerTest { @Autowired private MockMvc mockMvc; @MockBean private VoucherService voucherService; @Test @DisplayName("[API][GET] 바우처 리스트 조회") void getAllVouchers() throws Exception { given(voucherService.getVouchers()).willReturn(List.of(fixedVoucher, percentVoucher, fixedVoucher2)); mockMvc.perform(get("/api/v1/voucher").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$[0].voucherId").value(fixedVoucher.getVoucherId().toString())) .andExpect(jsonPath("$[1].voucherId").value(percentVoucher.getVoucherId().toString())) .andExpect(jsonPath("$[2].voucherId").value(fixedVoucher2.getVoucherId().toString())) .andDo(print()); } }