2025-07-06 00:20
Spring
使用MockMVC进行单元测试是一种常见的方式,可以模拟HTTP请求和响应,并对控制器的行为进行验证。在进行测试时,我们有时需要检查返回结果中的List和Map的内容是否符合预期。本文将介绍如何使用MockMVC进行这种结果的检查,并提供相应的案例代码。
Java@RunWith(SpringRunner.class)@WebMvcTest(YourController.class)public class YourControllerTest { @Autowired private MockMvc mockMvc; @Test public void testListResult() throws Exception { mockMvc.perform(get("/your-api")) .andExpect(status().isOk()) .andExpect(JSonPath("$.yourList[0].property1").value("value1")) .andExpect(JSonPath("$.yourList[0].property2").value("value2")) .andExpect(JSonPath("$.yourList[1].property1").value("value3")) .andExpect(JSonPath("$.yourList[1].property2").value("value4")); }}
Java@RunWith(SpringRunner.class)@WebMvcTest(YourController.class)public class YourControllerTest { @Autowired private MockMvc mockMvc; @Test public void testMapResult() throws Exception { mockMvc.perform(get("/your-api")) .andExpect(status().isOk()) .andExpect(JSonPath("$.yourMap.KEY1").value("value1")) .andExpect(JSonPath("$.yourMap.KEY2").value("value2")); }}
关于我们|免责条款|版权声明|侵权举报|隐私政策|联系我们
Copyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号