1. 概述
本文将介绍 Hoverfly Java 库 - 一个提供创建真实 API 存根/模拟的轻量级解决方案。对于需要模拟外部服务交互的开发场景,这个工具简单粗暴又高效。
2. Maven 依赖
使用 Hoverfly 只需添加一个 Maven 依赖:
<dependency>
<groupId>io.specto</groupId>
<artifactId>hoverfly-java</artifactId>
<version>0.8.1</version>
</dependency>
最新版本可在 这里 查找。
3. 模拟 API
首先配置 Hoverfly 运行在模拟模式。最简单的定义方式是使用 DSL。
通过实例化 HoverflyRule
快速上手:
public static final HoverflyRule rule
= HoverflyRule.inSimulationMode(dsl(
service("http://www.baeldung.com")
.get("/api/courses/1")
.willReturn(success().body(
jsonWithSingleQuotes("{'id':'1','name':'HCI'}"))));
关键点解析:
SimulationSource.dsl()
启动 API 定义HoverflyDSL.service()
定义接口和请求路径willReturn()
指定响应内容success()
设置响应状态和 body
4. JUnit 测试集成
使用 JUnit 测试模拟接口非常直接:
responseEntity<String> courseResponse
= restTemplate.getForEntity("http://www.baeldung.com/api/courses/1", String.class);
assertEquals(HttpStatus.OK, courseResponse.getStatusCode());
assertEquals("{\"id\":\"1\",\"name\":\"HCI\"}", courseResponse.getBody());
这里用 Spring Web 的 RestTemplate
发送 HTTP 请求,验证模拟接口是否按预期工作。
5. 添加延迟
延迟可全局设置,也可针对特定 HTTP 方法或接口调用。
为 POST 请求添加延迟的示例:
SimulationSource.dsl(
service("http://www.baeldung.com")
.post("/api/courses")
.willReturn(success())
.andDelay(3, TimeUnit.SECONDS)
.forMethod("POST")
)
⚠️ 注意:延迟设置需在 willReturn()
之后调用。
6. 请求匹配器
HoverflyMatchers
工厂类提供多种匹配器:
- URL 匹配:
exactMatch
(精确匹配)、globMatch
(通配符匹配) - Body 匹配:JSON/XML 精确匹配、JSONPath/XPath 匹配
默认使用 exactMatch
匹配 URL 和 body。综合示例:
SimulationSource.dsl(
service(matches("www.*dung.com"))
.get(startsWith("/api/student"))
.queryParam("page", any())
.willReturn(success())
.post(equalsTo("/api/student"))
.body(equalsToJson(jsonWithSingleQuotes("{'id':'1','name':'Joe'}")))
.willReturn(success())
.put("/api/student/1")
.body(matchesJsonPath("$.name"))
.willReturn(success())
.post("/api/student")
.body(equalsToXml("<student><id>2</id><name>John</name></student>"))
.willReturn(success())
.put("/api/student/2")
.body(matchesXPath("/student/name"))
.willReturn(success()));
)
匹配器功能解析:
| 匹配器类型 | 用途 | 示例场景 |
|------------------|-------------------------------|------------------------------|
| matches
| URL 通配符匹配 | www.*dung.com
|
| startsWith
| 路径前缀匹配 | /api/student
开头的路径 |
| any
| 接受任意参数值 | page
查询参数任意值 |
| equalsToJson
| JSON 精确匹配 | 完全匹配指定 JSON 结构 |
| matchesJsonPath
| JSONPath 存在性验证 | 检查 $.name
路径是否存在 |
| equalsToXml
| XML 精确匹配 | 完全匹配指定 XML 结构 |
| matchesXPath
| XPath 存在性验证 | 检查 /student/name
路径 |
7. 总结
本文介绍了 Hoverfly Java 库的核心用法: ✅ HTTP 服务模拟 ✅ DSL 接口配置 ✅ 延迟控制 ✅ 请求匹配器 ✅ JUnit 测试集成
完整代码示例见 GitHub 仓库。对于需要模拟外部 API 的测试场景,这个工具能帮你省去大量搭建 Mock 服务的时间。