Spring Boot JSON匹配测试
Spring Boot JSON匹配测试
一、环境准备与依赖配置
1.1 项目结构搭建
<!-- pom.xml 依赖配置 -->
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>com.jayway.jsonpath</groupId><artifactId>jsonpath-processor</artifactId><version>2.7.0</version></dependency>
</dependencies>
1.2 项目初始化
- 创建
src/main/java/com/example/demo
包结构 - 添加
Book
实体类(需包含id、name、type、description字段) - 配置
application.properties
基础参数
二、Book实体类创建
package com.example.demo;import javax.persistence.*;@Entity
@Table(name = "books")
public class Book {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;private String name;private String type;private String description;// Getter/Setter
}
三、测试用例配置
3.1 控制器接口实现
@RestController
@RequestMapping("/books")
public class BookController {@GetMapping("/{id}")public ResponseEntity<Book> getBookById(@PathVariable Long id) {Book book = new Book();book.setId(1L);book.setName("Spring Boot");book.setType("Tutorial");book.setDescription("Spring Boot application example");return ResponseEntity.ok(book);}
}
3.2 测试用例编写
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class BookControllerTest {@Autowiredprivate WebApplicationContext context;private MockMvc mockMvc;@Beforepublic void setup() {mockMvc = MockMvcBuilders.webAppContextSetup(context).build();}@Testpublic void testGetBookById() throws Exception {mockMvc.perform(get("/books/1")).andExpect(status().isOk()).andExpect(jsonPath("$.name").value("Spring Boot")).andExpect(jsonPath("$.type").value("Tutorial"));}
}
四、JSON匹配测试实现
4.1 基础匹配验证
@Test
public void testJsonMatch() throws Exception {mockMvc.perform(get("/books/1")).andExpect(status().isOk()).andExpect(jsonPath("$.id").isNumber()).andExpect(jsonPath("$.name").isString()).andExpect(jsonPath("$.type").isString()).andExpect(jsonPath("$.description").isString());
}
4.2 响应内容验证
@Test
public void testResponseBody() throws Exception {mockMvc.perform(get("/books/1")).andExpect(status().isOk()).andExpect(jsonPath("$.id").value(1)).andExpect(jsonPath("$.name").value("Spring Boot")).andExpect(jsonPath("$.type").value("Tutorial")).andExpect(jsonPath("$.description").value("Spring Boot application example"));
}
五、常见错误与解决方案
5.1 Content-Type不匹配错误
// 错误示例
@Test
public void testWrongContentType() throws Exception {mockMvc.perform(get("/books/1")).andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON));
}
错误信息示例:
Expected: "application/json"
Actual: "text/plain;charset=UTF-8"
解决方案:
// 正确配置
mockMvc.perform(get("/books/1").accept(MediaType.APPLICATION_JSON))
5.2 字段匹配失败
// 错误示例
@Test
public void testFieldMismatch() throws Exception {mockMvc.perform(get("/books/1")).andExpect(jsonPath("$.name").value("Spring Boot 2"));
}
错误信息示例:
Expected: "Spring Boot 2"
Actual: "Spring Boot"
解决方案:
// 正确匹配
mockMvc.perform(get("/books/1")).andExpect(jsonPath("$.name").value("Spring Boot"));
六、高级匹配技巧
6.1 多字段联合验证
mockMvc.perform(get("/books/1")).andExpect(jsonPath("$.id").isNumber()).andExpect(jsonPath("$.name").isString()).andExpect(jsonPath("$.type").isString()).andExpect(jsonPath("$.description").isString());
6.2 嵌套结构匹配
mockMvc.perform(get("/books/1")).andExpect(jsonPath("$.author.name").value("John Doe")).andExpect(jsonPath("$.author.email").value("john@example.com"));
6.3 响应时间验证
mockMvc.perform(get("/books/1")).andExpect(response().duration().lessThan(1000L));
七、扩展应用
7.1 使用JSONPath进行复杂查询
mockMvc.perform(get("/books")).andExpect(jsonPath("$[0].id").value(1)).andExpect(jsonPath("$[0].name").value("Spring Boot"));
7.2 响应头验证
mockMvc.perform(get("/books/1")).andExpect(header().exists("Content-Type")).andExpect(header().string("Content-Type").contains("application/json"));
八、总结
测试类型 | 适用场景 | 验证方式 | 注意事项 |
---|---|---|---|
状态码验证 | 基础功能验证 | andExpect(status().isOk()) | 需要确保接口正常响应 |
内容类型验证 | 响应格式验证 | andExpect(content().contentType(...)) | 需要配置正确的Content-Type |
字段值验证 | 数据准确性验证 | andExpect(jsonPath("$.field").value("value")) | 需要确保字段存在且值匹配 |
结构验证 | 嵌套数据验证 | andExpect(jsonPath("$.nested.field").value("value")) | 需要处理嵌套结构 |
响应时间验证 | 性能测试 | andExpect(response().duration().lessThan(...)) | 需要配置性能测试工具 |
通过以上实践,可以全面验证Spring Boot接口的JSON响应,确保数据格式、内容和结构符合预期要求。在实际开发中,建议结合单元测试和集成测试,构建完善的测试体系。