真实场景
Day 17 - API Testing
今日目标
- 使用 Playwright 做 API 测试。
- 理解 UI 测试与 API 测试如何配合。
学习时间安排(60–120 分钟)
| 时间 | 模块 | 做什么 |
|---|---|---|
| 0-20 分钟 | 核心概念与词汇 | 读概念表,重点理解 request fixture 和 APIRequestContext。 |
| 20-45 分钟 | 官方文档阅读 | 读 API testing 文档的 intro 和 request fixture 部分。 |
| 45-75 分钟 | 实操练习 | 写 3 条 API 测试:GET 列表、POST 创建、DELETE 清理。 |
| 75-105 分钟 | 示例代码改写 | 把一条 UI 流程的“准备数据”步骤改成 API 调用。 |
| 105-120 分钟 | 复盘与作业 | 完成今日问题,总结 UI+API 组合测试思路。 |
核心概念与词汇
| English | 中文 | 场景用法 |
|---|---|---|
request fixture | 请求夹具 | Use it when you send HTTP requests directly in tests. |
| APIRequestContext | API 请求上下文 | Use it when you reuse cookies and headers from the browser context for API calls. |
response.ok() | 响应成功判断 | Use it when you check the status code is 2xx. |
response.json() | JSON 解析 | Use it when you read and assert the response body. |
| status code | 状态码 | Use it when you assert 200, 201, 204, 404, 500 responses. |
| GET / POST / PUT / DELETE | HTTP 方法 | Use it when you read, create, update, or delete resources. |
| test data setup | 测试数据准备 | Use it when API calls create prerequisites faster than UI flows. |
| cleanup | 数据清理 | Use it when API calls delete test data after the test. |
| payload | 请求体 | Use it when you describe the JSON body sent with a request. |
| health check | 健康检查 | Use it when an API test verifies the service is up before UI tests. |
学习材料
- 必读:[API testing](https://playwright.dev/docs/api-testing)
- 必读:[APIRequestContext](https://playwright.dev/docs/api/class-apirequestcontext)(浏览主要方法)
- 选读:[Test fixtures - request](https://playwright.dev/docs/test-fixtures#request)
重点理解
示例:
import { test, expect } from '@playwright/test';
test('api test', async ({ request }) => {
const response = await request.get('/api/users');
expect(response.ok()).toBeTruthy();
const body = await response.json();
expect(body.length).toBeGreaterThan(0);
});
应用场景:
- 准备测试数据。
- 清理测试数据。
- 校验后端状态。
- 替代部分慢 UI 操作。
- 做接口健康检查。
实操步骤
写 3 条 API 测试:
- GET 列表。
- POST 创建数据。
- DELETE 清理数据。
如果没有真实 API,可以用公开测试 API 或本地 mock server。
示例代码
import { test, expect } from '@playwright/test';
test.describe('user api', () => {
test('create and delete a user', async ({ request }) => {
// POST 创建测试数据
const createRes = await request.post('/api/users', {
data: { username: 'auto_test_user', role: 'tester' },
});
expect(createRes.ok()).toBeTruthy();
const user = await createRes.json();
// GET 校验创建结果
const getRes = await request.get(`/api/users/${user.id}`);
expect(getRes.ok()).toBeTruthy();
expect(await getRes.json()).toMatchObject({ username: 'auto_test_user' });
// DELETE 清理数据
const deleteRes = await request.delete(`/api/users/${user.id}`);
expect(deleteRes.ok()).toBeTruthy();
});
});
常见坑
- 用
response.status()手写expect(status).toBe(200)也行,但忘了response.ok()覆盖整个 2xx 范围。 - API 测试和 UI 测试混在同一个文件里,职责不清。
- 创建了数据却忘了 DELETE 清理,第二次运行重复数据冲突。
- API 用的 baseURL 与 UI 不一致,环境切换时一半请求打错环境。
- 把 API 测试当成 UI 测试的替代品,丢掉了真实用户路径的验证。
今日产出
- 一个
api.spec.ts。 - 一套 UI + API 组合测试思路。
今日问题
- Playwright 的
requestfixture 是什么? - 哪些场景适合 API 测试,不适合 UI 测试?
- API 创建测试数据有什么好处?
- UI 和 API 断言如何互相补充?
- API 测试失败和 UI 测试失败如何区分?
复盘要点
- 测试金字塔提示我们:数据准备用 API,关键用户路径用 UI,两者组合而不是互相替代。
- API 测试快、稳定、定位精确,是回归集的主力;UI 测试覆盖端到端体验。
- 每个写操作的 API 测试都要有对应的清理路径,这是数据卫生的基本功。
AI 时代扩展:AI 辅助 Playwright 测试
新增概念
| English | 中文 |
|---|---|
| API test generation | API 测试生成 |
| contract verification | 契约校验 |
| data seeding | 数据播种 |
适用场景
让 AI 根据接口文档或响应示例生成 API 测试草稿,或者帮你设计“UI 验证 + API 准备数据”的组合流程。
可复用表达 / 提示词
这是接口文档:GET /api/orders 返回订单列表。请生成 3 条 API 测试草稿:正常、空数据、分页参数。
我的 UI 测试需要预先存在一个订单,请设计用 API 创建并清理该订单的完整流程。
追问加练
- AI 生成的 API 测试没有断言响应结构,你怎么补?
- 让 AI 从响应示例生成断言,风险是什么?
- 清理失败时(DELETE 报错),测试策略上怎么兜底?
今日作业
- 完成 3 条 API 测试并跑通。
- 把你的一条 UI 测试改造成“API 准备数据 + UI 验证 + API 清理”。
- 让 AI 根据你的接口响应生成断言草稿,人工核对后使用。