让 AI 编码助手接管 mock:录一次真实接口,CI 离线回放,一句话改返回

2 阅读10分钟

痛点:拿真实后端测客户端,又慢又不稳

我做移动端开发。客户端测试里最费劲的,往往不是写断言,而是让后端"配合":

  • 真正值得测的情况——空列表、支付失败、接口很慢、返回到一半就断了——真实服务器很难按需给出来。
  • 真实数据会变,测试账号会被用掉,同一轮用例今天过、明天不过。
  • Charles 这类代理能改返回,但得手点,一次一下:测试套件驱动不了它,AI 编码助手也驱动不了。
  • 另起一个 mock server,就得让 app 改连别的地址,每个返回还都要自己写。
  • 最隐蔽的是 CI 悄悄打到了真实后端:测试过了,却不是因为对的理由。

tunnel 是什么

tunnel 是一个本地的 HTTPS 代理加 mock server。手机、模拟器或者任何 HTTP 客户端,把 HTTP 代理指向它、信任它的 CA 证书,app 照旧请求自己真实的域名,不用改代码,也不用重新打包。tunnel 只解密你点名的 host,记下每一次调用,每个接口按它的规则作答:透传到真实服务器、录下来、从录制离线回放、返回一段 JSON、交给一段 JavaScript 处理,或者故意弄坏。规则下一个请求就生效。

它的两个特色是:AI 编码助手通过 MCP 或命令行驱动它,以及测试代码可以把它嵌进来。先花一分钟看看它能做什么。

一分钟试用:不用手机,curl 充当 app

先安装(需要 Node 22.18 或更新版本):

npm install -g tunnel-use   # 包名;命令叫 tunnel

在一个空目录里把服务起起来,再让当前 shell 里的 curl 走 tunnel、信任它的 CA。设备要做的,也就是这两件事:

mkdir try-tunnel && cd try-tunnel
tunnel init                    # 配置、CA 和录制都放在这里的 .tunnel/ 里
tunnel serve --background
export https_proxy=http://127.0.0.1:8890 CURL_CA_BUNDLE=.tunnel/ca.pem

第一步:录下一个真实的 HTTPS 返回。 用公开的 jsonplaceholder 做例子:

$ tunnel ssl add jsonplaceholder.typicode.com
SSL proxying is on
  include: jsonplaceholder.typicode.com
  exclude: (none)
$ tunnel record start
Recording passthrough traffic into session default (0 calls there already)
$ curl https://jsonplaceholder.typicode.com/todos/1
{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}
$ tunnel record stop
Recording stopped; session default holds 1 calls

只有用 ssl add 点了名的 host 才会被解密。录制是一个全局开关,不是某种响应模式:开着的时候,每个透传到真实服务器的调用都会存成单独一个文件。

第二步:离线回放,没录过的直接拒绝。

$ tunnel mode replay
replay · session default (1 recordings)
  an endpoint with no rule of its own is answered from the recordings, or 404 when nothing was recorded for it
$ curl https://jsonplaceholder.typicode.com/todos/1
{"userId": 1, "id": 1, "title": "delectus aut autem", "completed": false}
$ curl https://jsonplaceholder.typicode.com/todos/2
{"detail": "no rule or recording for GET:jsonplaceholder.typicode.com/todos/2", "key": "GET:jsonplaceholder.typicode.com/todos/2"}

todos/1 从录制作答,不碰网络;todos/2 从来没录过,tunnel 回 404 并说明原因,而不是把请求放到真实后端去,tunnel requests --unmatched 还会把这类调用列出来。CI 里要的正是这个:漏掉的请求会暴露出来,测试不会"碰巧"通过。

第三步:故意弄坏,再看 app 到底调了什么。

$ tunnel set GET jsonplaceholder.typicode.com/todos/1 --status 503 --delay 2 -d '{"error": "maintenance"}'
Configured GET:jsonplaceholder.typicode.com/todos/1  mode=json status=503
$ curl https://jsonplaceholder.typicode.com/todos/1
{"error": "maintenance"}
$ tunnel requests --each
    1  16:05:32.664  GET https://jsonplaceholder.typicode.com/todos/1  200  392ms  [passthrough]
    2  16:05:33.077  GET https://jsonplaceholder.typicode.com/todos/1  200  0ms  [replay]
    3  16:05:33.087  GET https://jsonplaceholder.typicode.com/todos/2  404  0ms  [unmatched]
    4  16:05:35.169  GET https://jsonplaceholder.typicode.com/todos/1  503  2000ms  [configured]

第四次调用等了两秒才拿到 503。请求日志的每一行都写着由谁作答:透传、回放、没匹配上,还是按规则。除了状态码和延迟,规则还能让连接挂住、直接断开,或者返回一段写到一半的 JSON(--fault)。

用一段 JS 改掉录制里的一个字段

很多时候测试要的不是一份从零编的假数据,而是"真实的返回,只改一个字段"。这就是 script 模式。先删掉上一步那条 503 规则,让这个接口回到回放:

tunnel rm GET jsonplaceholder.typicode.com/todos/1

再写一个 done.js:

function handler(ctx) {
  const rec = ctx.recorded()   // the real answer, as recorded
  rec.body.completed = true     // ... with one field changed
  return rec
}

交给这个接口:

$ tunnel set GET jsonplaceholder.typicode.com/todos/1 --script done.js
Configured GET:jsonplaceholder.typicode.com/todos/1  mode=script status=200
$ curl https://jsonplaceholder.typicode.com/todos/1
{"userId": 1, "id": 1, "title": "delectus aut autem", "completed": true}

ctx.recorded() 拿到的是这个接口录制的一份副本,改掉它的 body、status 或 headers 再原样返回,状态码、头和响应体就一起发出去。ctx 上还有请求本身的 method、path、query、headers、json(解析好的请求体),跨请求保留的 ctx.state,以及 ctx.reply(body, status, headers)。脚本用 JavaScript 或 TypeScript 写都行。

试完收尾:

tunnel stop && unset https_proxy CURL_CA_BUNDLE

录下来的放进仓库,在 CI 里回放

上面是单个接口。真实项目里的用法是:用测试账号把 app 的流程完整跑一遍、录下来,提交进客户端仓库,CI 里不连设备、不连后端,直接回放:

# 1. 在自己机器上,用设备把 app 的流程跑一遍
tunnel record start --session acct_a
tunnel record stop

# 2. 导出到客户端仓库
tunnel recordings export -o tests/mocks/recordings --session acct_a

# 3. 在 CI 里:没有设备,也没有后端
tunnel serve --background
tunnel recordings import tests/mocks/recordings --replace
tunnel mode replay --session acct_a    # 从 acct_a 的录制作答
tunnel apply tests/mocks/scenarios/empty_feed.json --replace
#    ……跑测试……
tunnel wait POST api.example.com/v5/pay --timeout 30
tunnel requests --unmatched
tunnel stop

每次调用存成 recordings/<session>/<host>/<METHOD>/<path>/<seq>.json,目录本身就是索引,同一个接口调两次,两份返回都留着。导出时 header 的值默认隐去(加 --raw 才保留)。提交之前还是要看一眼:这些是真实后端的真实返回。

AI-first:让 Claude Code / Codex 来驱动

一行命令接进去:

claude mcp add tunnel -- tunnel mcp        # Claude Code
codex mcp add tunnel -- tunnel mcp         # Codex

Cursor、Windsurf、Zed 这类读 JSON 配置的客户端,写这两个字段就行:

{"mcpServers": {"tunnel": {"command": "tunnel", "args": ["mcp"]}}}

tunnel mcp 只连已经在跑的服务,不会自己起一个:它是编辑器的子进程,编辑器关了它就退出,而代理是给手机连的,比编辑器窗口活得久。没有服务在跑时,工具调用会直接说明,并提示用 tunnel serve --background 起一个。

接好之后,用一句大白话提要求,比如「feed 接口返回空列表,然后告诉我 app 调了什么」。agent 会自己设规则、等 app 的请求到来、再把请求完整读回来,核对的是 app 实际发出的东西,而不是"规则设好了,应该没问题"。

一共 16 个工具。它们按 agent 实际要做的事来切分,而不是一个管理接口对应一个工具,因为每个工具的 schema 都会占着每一次 prompt:

用途工具
先看清现状status、guide
规则list_mocks、set_mock、delete_mock、apply_scenario
app 调了什么list_requests、get_request、wait_for_request、reset
整轮的开关set_config、decrypt
录制与回放record、list_recordings、get_recording
验证check:经代理口真打一发请求

schema 只能告诉 agent 某个字段叫什么、能填哪几个值,说不清回放怎么挑录制、ctx 里有什么、为什么查询串不参与匹配。所以还有 tunnel agents:它打印一份写给 agent 的指南,内容来自已安装的那个版本,而不是默认分支上的最新文档。MCP 里的 guide 工具返回的也是这一份。建议在项目的 CLAUDE.md 或 AGENTS.md 里放一行:

Working with tunnel (the local mock proxy)? Run `tunnel agents` first — it prints
the command reference and the handler(ctx) API for the installed version.

放一行,而不是把 25 KB 的指南整个粘进去:粘进去的话,每一次 prompt 都要带上它,而且它会停在粘贴时的版本。

不用 MCP 也一样能驱动。每条命令都能加 --json,输出可以直接解析;退出码可以拿来分支:0 成功,1 用户错误,2 管理 API 没有响应,3 tunnel wait 超时。tunnel check 经代理口真打一发请求,tunnel requests --each 看实际到了什么。

嵌进测试代码

另一个特色:每个用例在测试里自己设定返回,自己检查 app 调了什么。

Node 或 TypeScript 的测试套件,可以直接在自己的进程里起 tunnel,不用先起服务,也不用约定端口:

npm install --save-dev tunnel-use
import assert from 'node:assert/strict'
import { startTunnel } from 'tunnel-use'

// A simulator, an emulator and CI reach 127.0.0.1; a device on the network needs the default, 0.0.0.0
const tunnel = await startTunnel({ proxyHost: '127.0.0.1' })
try {
  await tunnel.setRule({ key: 'GET:api.example.test/v5/feed', mode: 'json', json_response: { cards: [] } })
  await tunnel.setRule({
    key: 'POST:api.example.test/v5/pay',
    handler: (ctx) => ctx.reply({ paid: ctx.json?.amount ?? 0 }, 201),
  })
  // ... drive the app through tunnel.proxyUrl; here one request stands in for it
  const answer = await tunnel.check('POST', 'http://api.example.test/v5/pay', {
    body: '{"amount": 100}',
    contentType: 'application/json',
  })
  assert.equal(answer.status, 201)
  const wait = await tunnel.waitForRequest({ key: 'POST:api.example.test/v5/pay', timeout: 5 })
  assert.equal(wait.timed_out, false)
  const exchange = await tunnel.getRequest(wait.seqs[0]!)
  assert.deepEqual(exchange.request.body, { amount: 100 })
} finally {
  await tunnel.stop()
}

startTunnel() 起的就是 tunnel serve 起的那一套:代理口、管理口、核心和脚本 worker。返回的句柄里有给 app 设代理用的 proxyUrl、设备要装的证书 caFile,以及调试时给 CLI 用的 adminUrl。规则可以写 JSON,也可以像上面 pay 那条一样直接给一个函数。每个方法对应一个管理 API 端点,所以场景文件里的规则可以原样传进 setRule()。

跑在 app 里的 Swift、Kotlin 用例没法在你的电脑上执行命令,就走 HTTP 管理 API。分工是:整轮测试共用的准备(起服务、导入录制、切到回放、装 CA)在宿主机上用 CLI 做;每个用例自己的事(应用这个用例的场景、清掉状态、等请求到来)在测试里经 HTTP 做。文档里有一个三十来行的 Swift 辅助类型,用起来是这样:

// in the test
try await Tunnel.apply([
    "replace": true,
    "mocks": [["key": "GET:api.example.com/v5/feed",
               "mode": "json",
               "json_response": ["code": 0, "cards": []]]],
])
// ... drive the app ...
XCTAssertTrue(try await Tunnel.waitFor("POST:api.example.com/v5/pay", timeout: 30))

Tunnel.apply 背后是 POST /__admin__/mocks/apply 加 POST /__admin__/state/reset,waitFor 是 GET /__admin__/requests/wait:等请求到来,而不是 sleep。从 iOS 模拟器访问管理 API 用 127.0.0.1:8000(它和 Mac 共用回环地址),Android 模拟器用 10.0.2.2:8000,USB 连的 Android 真机先 adb reverse tcp:8000 tcp:8000。

接真机和模拟器

tunnel serve 会打印要填进设备的代理地址(本机的局域网地址,端口 8890)和 CA 的下载地址。然后:

  • iPhone / iPad:无线局域网里当前网络的「配置代理」选「手动」,填本机局域网地址和 8890。
  • Android 手机:当前 Wi-Fi 的高级设置里,代理选手动,同样的地址和端口。
  • iOS 模拟器:它跟随 Mac 的系统代理。在 Mac 的网络设置里,把网页代理和安全网页代理都设成 127.0.0.1:8890,这是整台机器的设置,用完记得关掉。证书用 tunnel ca install --ios-simulator 装。
  • Android 模拟器:adb shell settings put global http_proxy 10.0.2.2:8890,用完 adb shell settings put global http_proxy :0 清掉。证书用 tunnel ca install --android 推到设备上,再从设置里安装。
  • Android 7 及以上:app 默认不信任用户自己装的 CA,需要在 app 的 network_security_config 里放开,比如只放在 debug 构建的 <debug-overrides> 里。

CA 第一次用时生成,之后一直不变:设备信任过一次就一直信任。给人盯着看的,还有 http://127.0.0.1:8000/ 上的一个面板,请求一到就显示出来。

已知限制

  • 解密过的 host 只走 HTTP/1.1。 想用 h2 的客户端会退回 HTTP/1.1;但在这些 host 上,WebSocket 升级会被拒绝,依赖 HTTP/2 的 gRPC 也走不了。这只影响你点名解密的 host。
  • 规则按 METHOD:host/path 匹配,查询串不参与匹配。 GraphQL 这种所有操作都打同一个端点的接口,要写一小段脚本,按请求体里的 operationName(ctx.json.operationName)分支。
  • Android 7+ 的证书信任,见上一节。

安装与链接

npm install -g tunnel-use   # 命令叫 tunnel
  • 需要 Node 22.18 或更新版本。不想全局安装的话,npx tunnel-use <命令> 可以直接跑上面任何一条。
  • TypeScript 写的,MIT 协议,运行时只依赖 Hono(hono 和 @hono/node-server 两个包)。
  • 中文文档齐全:github.com/e2e-next/tu…
  • 仓库:github.com/e2e-next/tu…

如果你也在为客户端测试里的后端数据头疼,欢迎试一试、提 issue,或者在评论里聊聊你们现在是怎么做的。觉得有用的话,点个 Star,能让更多遇到同样问题的人看到它。