Mock 服务搭建:WireMock 与 JSON Server

FreeGuideOnline 最新 2026-07-02

bash curl -O https://repo1.maven.org/maven2/com/github/tomakehurst/wiremock-jre8-standalone/2.35.0/wiremock-jre8-standalone-2.35.0.jar

2. 启动 Mock 服务器(默认监听 8080 端口):
```bash
java -jar wiremock-jre8-standalone-2.35.0.jar --port 8089

这里指定 --port 8089 避免与常见端口冲突。

1.2 创建第一个 Stub(桩)

Stub 定义了“请求-响应”的映射关系。通过 WireMock 的 Admin API(默认运行在相同端口)进行配置。

模拟一个 GET 接口,返回用户列表

执行以下 curl 命令创建 Stub:

curl -X POST http://localhost:8089/__admin/mappings \
  -H "Content-Type: application/json" \
  -d '{
    "request": {
        "method": "GET",
        "url": "/api/users"
    },
    "response": {
        "status": 200,
        "jsonBody": [
            {"id": 1, "name": "Alice"},
            {"id": 2, "name": "Bob"}
        ],
        "headers": {
            "Content-Type": "application/json"
        }
    }
}'

验证 Mock:

curl http://localhost:8089/api/users
# 返回 [{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}]

1.3 动态响应与请求匹配

WireMock 支持路径参数、查询参数、请求体匹配,以及基于 Handlebars 模板的动态响应。

示例:根据 URL 路径中的用户 ID 返回不同数据

{
  "request": {
    "method": "GET",
    "urlPattern": "/api/users/([0-9]+)"
  },
  "response": {
    "status": 200,
    "jsonBody": {
      "id": "{{request.path.[1]}}",
      "name": "User {{request.path.[1]}}"
    },
    "headers": {
      "Content-Type": "application/json"
    }
  }
}

访问 /api/users/5 将返回 {"id":"5","name":"User 5"}

1.4 高级特性速览

  • 模拟延迟:在 response 中添加 "fixedDelayMilliseconds": 2000
  • 故障模拟:设置 "fault": "CONNECTION_RESET_BY_PEER" 模拟网络错误。
  • 状态码模拟:如 "status": 500 返回服务器错误。
  • 录制与回放:WireMock 可以代理真实服务并录制请求,方便生成 Mock 数据。

停止服务器:直接结束进程即可。

第二部分:JSON Server 极速启动

JSON Server 是 Node.js 生态中最轻量的 Mock REST API 工具。你只需提供一个 JSON 文件,它就能在 30 秒内生成完整的 CRUD 接口。

2.1 安装与启动

npm install -g json-server

创建一个目录并准备好数据库文件 db.json

{
  "posts": [
    { "id": 1, "title": "json-server", "author": "typicode" }
  ],
  "comments": [
    { "id": 1, "body": "some comment", "postId": 1 }
  ],
  "profile": {
    "name": "admin"
  }
}

启动服务器:

json-server --watch db.json --port 3000

2.2 自动生成的 REST 接口

JSON Server 会根据 db.json 中的顶层键生成以下端点:

  • GET /posts —— 获取帖子列表
  • GET /posts/1 —— 获取 id 为 1 的帖子
  • POST /posts —— 创建帖子
  • PUT /posts/1 —— 更新帖子(全量覆盖)
  • PATCH /posts/1 —— 更新帖子(部分属性)
  • DELETE /posts/1 —— 删除帖子

测试示例

# 获取帖子列表
curl http://localhost:3000/posts

# 新建帖子
curl -X POST -H "Content-Type: application/json" \
  -d '{"title":"New Post","author":"Alice"}' \
  http://localhost:3000/posts

# 删除 id 为 2 的帖子
curl -X DELETE http://localhost:3000/posts/2

所有数据变更会自动持久化db.json 文件中,方便调试。

2.3 进阶查询与过滤

JSON Server 支持丰富的查询参数:

  • 过滤GET /posts?author=Alice
  • 全文搜索GET /posts?q=json
  • 分页GET /posts?_page=2&_limit=5
  • 排序GET /posts?_sort=title&_order=asc
  • 字段选择GET /posts?_select=title,author
  • 关系嵌入GET /posts?_embed=comments(关联查询)

2.4 添加中间件与自定义路由

如果需要更复杂的行为(如登录验证、慢速响应),可以创建一个 server.js 文件:

const jsonServer = require('json-server')
const server = jsonServer.create()
const router = jsonServer.router('db.json')
const middlewares = jsonServer.defaults()

server.use(middlewares)

// 自定义中间件:模拟延迟
server.use((req, res, next) => {
  setTimeout(next, 1000) // 所有请求延迟 1 秒
})

// 自定义路由
server.use(jsonServer.bodyParser)
server.post('/login', (req, res) => {
  if (req.body.username === 'admin') {
    res.jsonp({ token: 'fake-jwt-token' })
  } else {
    res.status(401).jsonp({ error: 'Bad credentials' })
  }
})

server.use(router)
server.listen(4000, () => {
  console.log('JSON Server with custom routes is running on port 4000')
})