使用MockMvc以JSON格式传递数组参数的完整指南
在Spring Boot应用测试中,Mock是一个非常强大的工具,它允许我们在不启动完整服务器的情况下测试控制器,而MockMvc则是Spring Test框架中用于对Spring MVC控制器进行测试的工具,在实际开发中,我们经常需要测试接收数组参数的接口,本文将详细介绍如何使用MockMvc以JSON格式传递数组参数。
基本环境准备
确保你的项目中已经添加了必要的依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
准备测试控制器
假设我们有一个简单的控制器,接收一个字符串数组参数:
@RestController
@RequestMapping("/api")
public class ArrayController {
@PostMapping("/process-array")
public ResponseEntity<String> processArray(@RequestBody List<String> items) {
return ResponseEntity.ok("Received " + items.size() + " items: " + items);
}
}
使用MockMvc传递JSON数组
1 使用perform()和post()方法
@SpringBootTest
@AutoConfigureMockMvc
public class ArrayControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testProcessArrayWithJson() throws Exception {
String[] items = {"item1", "item2", "item3"};
mockMvc.perform(post("/api/process-array")
.contentType(MediaType.APPLICATION_JSON)
.content(new ObjectMapper().writeValueAsString(items)))
.andExpect(status().isOk())
.andExpect(content().string("Received 3 items: [item1, item2, item3]"));
}
}
2 使用JSON数组字符串
你也可以直接构造JSON字符串:
@Test
public void testProcessArrayWithJsonString() throws Exception {
String jsonArray = "[\"item1\", \"item2\", \"item3\"]";
mockMvc.perform(post("/api/process-array")
.contentType(MediaType.APPLICATION_JSON)
.content(jsonArray))
.andExpect(status().isOk())
.andExpect(content().string("Received 3 items: [item1, item2, item3]"));
}
处理复杂对象数组
如果需要传递复杂对象数组,可以按照以下方式:
1 定义复杂对象
public class Item {
private String id;
private String name;
private int quantity;
// getters and setters
}
2 测试复杂对象数组
@Test
public void testProcessObjectArray() throws Exception {
Item[] items = {
new Item("1", "Item 1", 10),
new Item("2", "Item 2", 20)
};
mockMvc.perform(post("/api/process-array")
.contentType(MediaType.APPLICATION_JSON)
.content(new ObjectMapper().writeValueAsString(items)))
.andExpect(status().isOk());
}
常见问题与解决方案
1 数组为空的情况
@Test
public void testEmptyArray() throws Exception {
mockMvc.perform(post("/api/process-array")
.contentType(MediaType.APPLICATION_JSON)
.content("[]"))
.andExpect(status().isOk())
.andExpect(content().string("Received 0 items: []"));
}
2 数组元素包含特殊字符
@Test
public void testArrayWithSpecialChars() throws Exception {
String[] items = {"item1", "item@2", "item#3"};
mockMvc.perform(post("/api/process-array")
.contentType(MediaType.APPLICATION_JSON)
.content(new ObjectMapper().writeValueAsString(items)))
.andExpect(status().isOk());
}
高级用法:使用参数化测试
使用JUnit 5的参数化测试可以更高效地测试多种数组情况:
@ParameterizedTest
@CsvSource({
"'[\"a\", \"b\", \"c\"]', 3",
"'[\"x\", \"y\"]', 2",
"'[]', 0"
})
public void testDifferentArrays(String jsonArray, int expectedSize) throws Exception {
mockMvc.perform(post("/api/process-array")
.contentType(MediaType.APPLICATION_JSON)
.content(jsonArray))
.andExpect(status().isOk())
.andExpect(content().string(containsString("Received " + expectedSize + " items")));
}
通过本文的介绍,你应该已经了如何使用MockMvc以JSON格式传递数组参数,关键点包括:
- 使用
contentType(MediaType.APPLICATION_JSON)设置请求头 - 使用
ObjectMapper.writeValueAsString()将数组转换为JSON字符串 - 直接构造JSON字符串也是一种有效的方法
- 可以处理简单数组和复杂对象数组
- 注意处理边界情况如空数组
MockMvc的灵活性和强大功能使得Spring MVC控制器的测试变得简单高效,这些技巧将大大提高你的测试效率。



还没有评论,来说两句吧...