当前位置: 首页 > news >正文

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响应,确保数据格式、内容和结构符合预期要求。在实际开发中,建议结合单元测试和集成测试,构建完善的测试体系。

http://www.dtcms.com/a/458146.html

相关文章:

  • 9.MySQL索引
  • Java--多线程基础知识(四)
  • 实现接口文档与测试脚本的实时同步
  • 用vis做的简单网站汉语言专业简历制作说明
  • 如何查看网站开发语言.net core 网站开发
  • 第5章:聊天记忆(Chat Memory)—让 AI 记住上下文
  • RAG创新方案支REFRAG
  • 高通收购Arduino,加速开发者获取领先的边缘计算与AI技术
  • 住房和城市建设厅网站wordpress本地网站怎么访问
  • mongo 适应场景
  • 沧浪企业建设网站价格win8导航网站模板
  • 实战篇:智能选配合理之轨——工业远心镜头选型终极攻略
  • 深入理解队列(Queue):从原理到实践的完整指南
  • 网站开发企业组织结构集团有限公司
  • 营销型网站建设 博客网页制作怎么做第二页
  • 网站前台功能傻瓜式网站
  • 初识Redis:理解其定位与适用场景
  • 网站客户端制作教程广州抖音推广公司
  • 项目绩效改进方案
  • 【碎片化学习】工具文:计算机通用术语中常见的100个英文单词
  • 解决 VNC 远程连接无法复制粘贴的完整指南
  • 门户网站建设方案ppt刷排名seo
  • 雅特力AT32单片机的使用 , 工程建立.
  • 交易平台网站建设项目需求asp.net网站开发技术
  • 手机淘宝客网站怎么做的网页设计制作实训报告模板
  • 11.1 kubectl命令行工具
  • SSM房屋租赁管理系统d97n3(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
  • 不备案的网站需要注销吗优化大师 win10下载
  • 做盗链网站八大员继续教育入口
  • 长春网站建设首选网诚传媒_正规网站建设服务中心