返回首页

API 测试:检查清单和自动测试

本文描述了 API 测试的系统化方法:检查类别、Postman 和 Jest+axios 示例、检查清单、AI 在用例生成中的作用。适用于中高级 QA 和开发者。

API 测试:从 Postman 到 AI 用例生成
Advertisement 728x90

API测试清单:从状态码到AI自动化

API测试涵盖多个核心领域。任何环节的疏漏都可能导致生产环境中的隐藏缺陷。

状态码

验证返回的状态码是否符合预期场景:

| 场景 | 预期状态码 |

Google AdInline article slot

|----------|---------------|

| 成功创建 | 201 |

| 资源未找到 | 404 |

Google AdInline article slot

| 权限不足 | 403 |

| 未认证 | 401 |

| 数据无效 | 400/422 |

Google AdInline article slot

| 服务器错误 | 500 |

常见陷阱:返回200但响应体中包含错误信息——这违背了REST原则。

响应结构

  • 必填字段必须存在。
  • 数据类型需与预期一致(如数字而非字符串)。
  • 嵌套对象不能为null。
  • 数组不应被误认为对象。

边界情况

测试极限条件:

  • 空请求体。
  • 缺少必填字段。
  • 字段为空字符串。
  • 数值:0、负数、最大整数值。
  • 字符串:1个字符、最大长度、特殊字符、SQL/XSS攻击载荷。

认证与请求头

  • 无令牌:401。
  • 过期令牌:401。
  • 无效令牌:403。
  • 只读用户执行写操作:403。

请求头:Content-Type、CORS、速率限制。

在Postman中测试

使用 Tests 标签页编写JavaScript脚本,用于响应后校验。

基础断言

// 状态码和响应时间
pm.test("状态码为200", () => {
    pm.response.to.have.status(200);
});

pm.test("响应时间<500毫秒", () => {
    pm.expect(pm.response.responseTime).to.be.below(500);
});

// 内容类型
pm.test("返回JSON", () => {
    pm.response.to.have.header("Content-Type", "application/json; charset=utf-8");
});

结构与类型校验

const response = pm.response.json();

pm.test("id字段存在", () => {
    pm.expect(response).to.have.property("id");
});

pm.test("id是数字类型", () => {
    pm.expect(response.id).to.be.a("number");
});

pm.test("email不为空", () => {
    pm.expect(response.email).to.be.a("string").and.not.empty;
});

负向测试:无令牌访问

pm.test("无令牌返回401", () => {
    pm.response.to.have.status(401);
});

const response = pm.response.json();
pm.expect(response).to.have.property("message");

/login 接口返回的令牌保存至环境变量:pm.environment.set("auth_token", response.token);。在请求头中通过 {{auth_token}} 引用该令牌。

使用Jest + axios实现自动化测试

在CI/CD流程中,建议以代码形式编写测试。以下为 /users/:id 接口示例:

const axios = require("axios");

const BASE_URL = "https://api.example.com";
const TOKEN = process.env.API_TOKEN;

const client = axios.create({
    baseURL: BASE_URL,
    headers: { Authorization: `Bearer ${TOKEN}` }
});

describe("GET /users/:id", () => {

    test("根据ID获取用户", async () => {
        const response = await client.get("/users/1");

        expect(response.status).toBe(200);
        expect(response.data).toMatchObject({
            id: expect.any(Number),
            email: expect.any(String),
            name: expect.any(String),
        });
    });

    test("不存在的用户返回404", async () => {
        await expect(client.get("/users/999999"))
            .rejects.toMatchObject({
                response: { status: 404 }
            });
    });

    test("无令牌返回401", async () => {
        await expect(axios.get(`${BASE_URL}/users/1`))
            .rejects.toMatchObject({
                response: { status: 401 }
            });
    });

});

运行命令:npx jest user.test.js

通用测试清单

正向场景:

  • 有效数据 → 正确状态码。
  • 响应结构与文档一致。
  • 必填字段齐全。
  • 数据类型正确。
  • 响应时间在合理范围内。

负向测试:

  • 无认证 → 401。
  • 令牌错误 → 403。
  • 字段缺失 → 400/422。
  • 类型错误 → 400/422。
  • 资源不存在 → 404。
  • 请求体为空 → 验证失败。

边界情况:

  • 最小/最大值。
  • 零或负数。
  • 空字符串。
  • 特殊字符/Unicode。
  • 超长字符串。

安全测试:

  • SQL注入。
  • XSS跨站脚本。
  • IDOR(ID猜测漏洞)。

AI驱动的自动化测试

AI可基于OpenAPI规范自动生成测试用例——包括正向、负向及边界场景,并输出为Jest格式。

提示词示例:“根据[schema]生成POST /users接口的测试用例,使用真实数据。”

利用大模型自动分析响应内容:

async function validateWithAI(prompt, response) {
    // 调用Claude/GPT评估响应相关性
    // ...
    return data.content[0].text.trim() === "YES";
}

AI还能智能生成边缘数据:如从右到左文本、表情符号、不可见Unicode字符。

但请注意:AI无法替代业务逻辑理解(例如非高级用户折扣不得超过100%)。

最重要的几点

  • 严格按场景验证状态码——绝不因错误而返回200。
  • 使用类似JSONPath的断言方式校验响应结构与类型。
  • 在CI/CD中用Jest/axios自动化负向与边界测试。
  • 借助AI处理重复任务:测试生成、结果分析、边缘数据构造。
  • 将此清单作为每个接口的强制模板,确保测试完整性。

— Editorial Team

Advertisement 728x90

继续阅读