【问题标题】:Compare ResponseEntities Spring Test MockMVC比较 ResponseEntities Spring Test MockMVC
【发布时间】:2019-12-20 00:12:39
【问题描述】:

是否可以使用 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 // );

}

【问题讨论】:

标签: spring-boot httpresponse spring-test mockmvc


【解决方案1】:

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

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

ObjectMapper mapper = new ObjectMapper();

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

现在你可以使用

.andExpect(MockMvcResultMatchers.content().json(expected.toString());

对我有用

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-29
    • 1970-01-01
    • 2016-08-02
    • 1970-01-01
    相关资源
    最近更新 更多