共计 1534 个字符,预计需要花费 4 分钟才能阅读完成。
Using JsonPath in MockMVC Test
BeerController
@RequestMapping("/api/v1/beer")
@RestController
public class BeerController {
private final BeerService beerService;
@GetMapping(path = {"/{beerId}"},produces = {"application/json"})
public ResponseEntity<BeerDto> getBeerById(@PathVariable("beerId") UUID beerId){return new ResponseEntity<>(beerService.findBeerById(beerId), HttpStatus.OK);
}
}
BeerControllerTest
import static org.hamcrest.core.Is.is;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@ExtendWith(MockitoExtension.class)
class BeerControllerTest {
@Mock
BeerService beerService;
@InjectMocks
BeerController beerController;
MockMvc mockMvc;
BeerDto validBeer;
@BeforeEach
void setUp() {validBeer = BeerDto.builder().id(UUID.randomUUID())
.version(1)
.beerName("Beer1")
.beerStyle(BeerStyleEnum.PALE_ALE)
.price(new BigDecimal("12.99"))
.quantityOnHand(4)
.upc(123456789012L)
.createdDate(OffsetDateTime.now())
.lastModifiedDate(OffsetDateTime.now())
.build();
mockMvc = MockMvcBuilders.standaloneSetup(beerController).build();}
@Test
void testGetBeerById() throws Exception {given(beerService.findBeerById(any())).willReturn(validBeer);
mockMvc.perform(get("/api/v1/beer/" + validBeer.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$.id", is(validBeer.getId().toString())))
.andExpect(jsonPath("$.beerName", is("Beer1")));
}
}
正文完