Postman API 测试进阶:从请求调试到自动化测试

Postman 是 API 开发和测试的必备工具。除了基础的请求调试,Postman 还提供了强大的自动化测试能力。

一、测试脚本编写

Postman 支持在请求前后执行 JavaScript 脚本。

Pre-request Script

// 在请求发送前执行
const timestamp = new Date().getTime();
pm.variables.set("timestamp", timestamp);

// 生成签名
const apiKey = pm.environment.get("API_KEY");
const signature = CryptoJS.HmacSHA256(timestamp.toString(), apiKey).toString();
pm.request.headers.add({
    key: "X-Signature",
    value: signature
});

Tests Script

// 验证状态码
pm.test("Status code is 200", function () {
    pm.response.to.have.status(200);
});

// 验证响应体
pm.test("Response has data", function () {
    const jsonData = pm.response.json();
    pm.expect(jsonData).to.have.property("data");
    pm.expect(jsonData.data).to.be.an("array");
});

// 保存变量供后续请求使用
const token = pm.response.json().token;
pm.collectionVariables.set("auth_token", token);

二、集合和文件夹

API Collection
├── Auth
│   ├── Login
│   └── Refresh Token
├── Users
│   ├── GET /users
│   ├── POST /users
│   └── DELETE /users/:id
└── Products
    ├── GET /products
    └── POST /products

三、环境管理

环境 变量示例
Development base_url: http://localhost:3000
Staging base_url: https://staging-api.example.com
Production base_url: https://api.example.com

四、Newman CLI 集成

# 安装 Newman
npm install -g newman

# 运行集合
newman run collection.json   -e environment.json   --reporters cli,htmlextra

# CI/CD 集成
newman run collection.json   --reporters junit   --reporter-junit-export results.xml

五、Monitors 监控

Postman Monitors 可以定时运行 API 测试,监控 API 健康状态。