Controllor test ์‘๋‹ต ๊ฒฐ๊ณผ ๊ฒ€์ฆ jsonPath

Controllor test ์‘๋‹ต ๊ฒฐ๊ณผ ๊ฒ€์ฆ jsonPath

๊ฐ„๋‹จ ์š”์•ฝ / ๋น„๊ณ 
์ž‘์„ฑ์ผ
May 12, 2022
์ž‘์„ฑ์ž
๊ธฐ์ˆ  ํƒœ๊ทธ
ํ…Œ์ŠคํŠธ
๊ฐ•์˜์—์„œ api controller test ์— mockMvc๋ฅผ ํ™œ์šฉํ•ด์„œ ๊ฒฐ๊ณผ์— ๋Œ€ํ•œ ๊ฒ€์ฆ์„ status ์ •๋„๋กœ๋งŒ ํ•˜๊ณ  ์žˆ๋Š”๋ฐ
 
jsonPath ๋ฅผ ํ™œ์šฉํ•ด์„œ ์‘๋‹ต๋ฐ›์€ json์˜ ๊ฒฐ๊ณผ๋ฅผ ๊ฒ€์ฆํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
$๋กœ ์‹œ์ž‘ํ•˜๋Š” json path ํ‘œํ˜„์‹์œผ๋กœ ๊ฒ€์ฆํ•˜๊ณ ์ž ํ•˜๋Š” value๊ฐ’์„ ์„ ํƒํ•˜์—ฌ ๊ฒ€์ฆํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
 
 

ํ™œ์šฉ์˜ˆ์‹œ

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()); } }
  • jsonPath์•ˆ์˜ ํŒจํ„ด ๋งค์นญ ์‚ฌ์šฉ๋ฐฉ๋ฒ• ์ฐธ๊ณ  :