比较ResponseEntities春季测试MockMVC

时间:2019-08-13 12:25:58

标签: spring-boot httpresponse spring-test mockmvc

是否可以使用MockMCV比较实际的ResponseEntity和从控制器返回的那个?

@Test
public void testStatusGetAllCars() throws Exception {
    ResponseEntity<?> expectedResponse = carController.getAllCars();

    mockMVC.perform(MockMvcRequestBuilders.get("/api/cars"))
    .andDo(MockMvcResultHandlers.print())
    .andExpect(MockMvcResultMatchers.status().isOk())
    .andExpect(MockMvcResultMatchers.content().contentType("application/hal+json;charset=UTF-8"))
    .andExpect( /// compare goes here // );

}

1 个答案:

答案 0 :(得分:0)

controller 返回 json 作为 ResponseEntity 的主体。 您可以使用 jackson 并使用 NodeObject 和 Objectmapper 创建您期望的 json 对象

https://attacomsian.com/blog/jackson-create-json-object

checkFields() {

// Clear the validator every time a change occurs
this.employerBasicsForm.controls.tax.clearValidators();

// If both fields have been filled in, then make tax required
if ((this.employerBasicsForm.controls.openDate.value != null && this.employerBasicsForm.controls.closeDate.value != null))
{
  this.employerBasicsForm.controls.tax.setValidators([Validators.required]);
}

// Update the validity
this.employerBasicsForm.controls.tax.updateValueAndValidity();
}

现在你可以使用

ObjectMapper mapper = new ObjectMapper();

NodeObject expected = mapper.createObjectNode();
//then put your fields

它对我有用