[使用JUint5在Mockmvc中传递列表对象

问题描述 投票:0回答:1

我正在使用JUnit5进行集成测试。我有一个需要传递到终点的对象列表。 Mockmvc的content参数仅包含字符串。我如何传递这个物体?任何想法将不胜感激。

这是我的代码

    Customer cust1 = Customer.builder().name("Syed")
            .location("India").build();
Customer cust2 = Customer.builder().name("Ali")
            .location("India").build();


    List<Customer> customers = Arrays.asList(cust1, cust2); --> This needs to be passed. 

    MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post("/process")

            .content(customers) --> Compilation error here
            .contentType(MediaType.APPLICATION_JSON)
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andReturn();

我该如何解决

java mockito junit5
1个回答
0
投票

您可以自动连接ObjectMapper并将对象(customers)转换为字符串:

@Autowired
private ObjectMapper;

// in your method
.content(objectMapper.writeValueAsString(customers))
// ..

完整示例:

MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post("/process")

    .content(objectMapper.writeValueAsString(customers)) // change applied
    .contentType(MediaType.APPLICATION_JSON)
    .accept(MediaType.APPLICATION_JSON))
    .andExpect(status().isOk())
    .andReturn();
© www.soinside.com 2019 - 2024. All rights reserved.