
最近折腾了用大语言模型(LLM)来自动生成和维护 API 测试,踩了不少坑,这篇把实操经验说清楚。
需求不是"帮我生成测试数据"这种简单活儿——我想让 AI 真正理解我的 API 接口,自动写测试用例,并且当接口变更时能同步更新测试代码。
下面是我的完整踩坑记录,代码都是实际跑通过的。
维护的 API 主要处理用户管理、计费和 webhook 回调,大约 40 个接口。每次加新功能,光改测试就要花半小时到一小时。一个月下来少说也要更新 4-5 次,这时间成本就很可观了。
我的目标很明确:
第一反应很简单:把 YAML 文件整个复制粘贴进去,跟 AI 说"帮我写测试"。
结果: 生成了一堆看起来很漂亮的测试代码,pytest fixtures、参数化输入、响应校验,一应俱全。跑一下试试——全部挂掉。
问题很隐蔽:AI 自己编造了一些接口里根本不存在的返回字段。比如我的 /users/{id} 接口实际返回的是 {"id", "email", "created_at"},但 AI 生成的测试断言了 response.json()["name"],这个字段根本不存在。
教训: 大模型会"幻想"出 API 的数据结构。生成完测试一定要对照实际 Schema 校验一遍再跑。
第二次换了个思路:写个 Python 脚本,把 API 规范的结构化信息提取出来喂给 AI:
import json # Extract schema into a flat structure the model can't misinterpret
with open("openapi.json") as f: spec = json.load(f) for path, methods in spec["paths"].items(): for method, details in methods.items(): # Pull out response status codes and schemas if "responses" in details: for status, resp in details["responses"].items(): schema = resp.get("content", {}).get( "application/json", {} ).get("schema", {}) print(f"{method.upper()} {path} → {status}") print(json.dumps(schema, indent=2)) print("---")
这次效果好多了。不直接喂原始规范文件,而是先计算出一个结构化的摘要——这样 AI 产生幻觉的概率大幅下降。测试一次通过率从 0% 提升到了 70% 左右。
70% 的一次通过率虽然比之前好,但剩下 30% 还得手动修。于是加了反馈循环:
# 1. Generate tests
ai-cli generate-tests --spec openapi.json > test_api_v2.py # 2. Run them, capture failures
pytest test_api_v2.py -q --tb=short > failures.log 2>&1 # 3. Feed failures back to the AI
ai-cli fix-tests --source test_api_v2.py --failures failures.log > test_api_v3.py
这样第二轮迭代下来,一次通过率能到 95%。剩下的 5% 基本都是规范本身描述不清楚的情况——比如限流响应的具体行为、条件性返回字段之类的。
核心心得: 别指望一次生成完美的测试。两轮生成加真实错误反馈,比花大量时间调 prompt 效果好得多。
折腾了一个月之后,最终定型的架构是这样的:
┌─────────────────┐ ┌──────────────────┐
│ OpenAPI Spec │────▶│ Schema Extractor │
│ (openapi.json) │ │ (Python script) │
└─────────────────┘ └────────┬─────────┘ │ structured context ▼ ┌──────────────────┐ │ AI Test Gen │ │ (Prompt + LLM) │ └────────┬─────────┘ │ test file ▼ ┌──────────────────┐ │ pytest run │ └────────┬─────────┘ │ failures ▼ ┌──────────────────┐ │ AI Fix Pass │◀─── loop until pass └──────────────────┘
Prompt 模板是关键,这个规则集让测试质量提升最明显:
You are an API testing expert. Given the following endpoint schemas,
generate a pytest test suite. RULES:
- Only assert fields that exist in the response schema
- For each endpoint, test: 200 OK, 404 Not Found, and at least one edge case (invalid input, missing auth, etc.)
- Use pytest fixtures for shared setup
- Do NOT import libraries not in requirements.txt ENDPOINT SCHEMAS:
{structured_context}
最后一条规则——限制 import 的库——比预想的省心很多。之前版本经常引入一些我没装过的库,调半天 prompt 都治不住。
| 指标 | 纯手动 | AI 辅助 |
|---|---|---|
| 写完 40 个接口的测试套件 | 约 4 小时 | 约 45 分钟 |
| 测试一次通过率 | 约 85%(人工疏漏) | 约 70%(幻觉问题) |
| 经过反馈循环后 | N/A | 约 95% |
| 接口变更后更新测试 | 约 45 分钟 | 约 15 分钟 |
| 边界情况覆盖 | 依赖个人经验 | 出乎意料地全面 |
省下来的时间是真金白银,但核心价值不是"省了时间",而是"不再从零开始"。我还是会 review 每一行 AI 生成的代码,只是省掉了从头写的苦力活。
AI 不会取代 API 测试工程师,但把脏活累活自动化这块确实很香。我的完整工作流:
现在我把省下来的时间花在思考"测什么"而不是"怎么测"上。这个转变才是真正的收益。