以下代码说明了使用testng和嘲笑对post方法的测试。我在行assertThat(outputInJson).isEqualTo(inputInJson)遇到错误。创建要约时,控制器类的post方法返回响应实体对象。
@Test
public void testCreateOffer() throws Exception {
Offer offer = new Offer("SE", new Date(), 10);
MockHttpServletRequest request = new MockHttpServletRequest();
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{jobTitle}")
.buildAndExpand(offer.getJobTitle()).toUri();
String inputInJson = this.mapToJson(ResponseEntity.created(location).build());
Mockito.when(offerService.createOffer(Mockito.any(Offer.class))).thenReturn(offer);
RequestBuilder requestBuilder = MockMvcRequestBuilders.post("/offers").accept(MediaType.APPLICATION_JSON)
.content(inputInJson).contentType(MediaType.APPLICATION_JSON);
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
MockHttpServletResponse response = result.getResponse();
String outputInJson = response.getContentAsString();
assertThat(outputInJson).isEqualTo(inputInJson);
assertThat(response.getStatus()).isEqualTo(HttpStatus.CREATED.value());
}
private String mapToJson(Object object) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.writeValueAsString(object);
}
和控制器类发布方法
@PostMapping("/offers")
public ResponseEntity<Object> createOffer(@Valid @RequestBody Offer offer) {
Offer uoffer = offerService.createOffer(offer);
URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{jobTitle}")
.buildAndExpand(uoffer.getJobTitle()).toUri();
return ResponseEntity.created(location).build();
}