搬瓦工 VPS 搭建 Postman API 测试自动化教程
Postman 是全球最流行的 API 开发和测试平台,不仅提供图形化的请求发送工具,还支持自动化测试、环境变量管理和 CI/CD 集成。对于部署在搬瓦工 VPS 上的 API 服务,使用 Postman 及其命令行工具 Newman 可以建立完整的自动化测试流程。本教程将介绍如何编写 Postman 测试集合,使用 Newman 在服务器上执行自动化测试,并集成到 CI/CD 流水线中。
一、Postman 核心概念
- Collection:请求集合,组织一组相关的 API 请求,支持文件夹分组。
- Environment:环境变量,管理不同环境(开发/测试/生产)的配置。
- Pre-request Script:请求前脚本,在发送请求前执行 JavaScript 代码。
- Tests:测试脚本,在收到响应后执行断言验证。
- Newman:Postman 的命令行运行器,可在服务器上无界面运行测试。
二、安装 Newman
# 安装 Node.js(如果未安装)
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
apt install -y nodejs
# 安装 Newman 及报告插件
npm install -g newman newman-reporter-htmlextra newman-reporter-json-summary
# 验证安装
newman --version
三、编写测试集合
3.1 创建 Collection 文件
mkdir -p /opt/api-tests && cd /opt/api-tests
cat > collection.json <<'ENDJSON'
{
"info": {
"name": "用户管理 API 测试",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"item": [
{
"name": "健康检查",
"request": {
"method": "GET",
"url": "{{baseUrl}}/health"
},
"event": [
{
"listen": "test",
"script": {
"exec": [
"pm.test('状态码为 200', function () {",
" pm.response.to.have.status(200);",
"});",
"pm.test('响应时间小于 500ms', function () {",
" pm.expect(pm.response.responseTime).to.be.below(500);",
"});"
]
}
}
]
},
{
"name": "创建用户",
"request": {
"method": "POST",
"url": "{{baseUrl}}/users",
"header": [
{"key": "Content-Type", "value": "application/json"},
{"key": "Authorization", "value": "Bearer {{authToken}}"}
],
"body": {
"mode": "raw",
"raw": "{\"name\": \"测试用户\", \"email\": \"test@example.com\", \"age\": 25}"
}
},
"event": [
{
"listen": "test",
"script": {
"exec": [
"pm.test('用户创建成功', function () {",
" pm.response.to.have.status(201);",
"});",
"pm.test('返回用户ID', function () {",
" var jsonData = pm.response.json();",
" pm.expect(jsonData).to.have.property('id');",
" pm.environment.set('userId', jsonData.id);",
"});",
"pm.test('返回正确的用户名', function () {",
" var jsonData = pm.response.json();",
" pm.expect(jsonData.name).to.eql('测试用户');",
"});"
]
}
}
]
},
{
"name": "获取用户详情",
"request": {
"method": "GET",
"url": "{{baseUrl}}/users/{{userId}}",
"header": [
{"key": "Authorization", "value": "Bearer {{authToken}}"}
]
},
"event": [
{
"listen": "test",
"script": {
"exec": [
"pm.test('获取用户成功', function () {",
" pm.response.to.have.status(200);",
"});",
"pm.test('用户数据结构正确', function () {",
" var jsonData = pm.response.json();",
" pm.expect(jsonData).to.have.property('id');",
" pm.expect(jsonData).to.have.property('name');",
" pm.expect(jsonData).to.have.property('email');",
"});"
]
}
}
]
},
{
"name": "删除用户",
"request": {
"method": "DELETE",
"url": "{{baseUrl}}/users/{{userId}}",
"header": [
{"key": "Authorization", "value": "Bearer {{authToken}}"}
]
},
"event": [
{
"listen": "test",
"script": {
"exec": [
"pm.test('删除成功', function () {",
" pm.response.to.have.status(204);",
"});"
]
}
}
]
}
]
}
ENDJSON
3.2 创建环境配置
cat > env-production.json <<'ENDJSON'
{
"name": "生产环境",
"values": [
{"key": "baseUrl", "value": "https://api.example.com/v1", "enabled": true},
{"key": "authToken", "value": "your_api_token_here", "enabled": true}
]
}
ENDJSON
cat > env-staging.json <<'ENDJSON'
{
"name": "测试环境",
"values": [
{"key": "baseUrl", "value": "http://localhost:3000/v1", "enabled": true},
{"key": "authToken", "value": "test_token_2026", "enabled": true}
]
}
ENDJSON
四、运行 Newman 测试
4.1 基本运行
# 运行测试(使用测试环境)
newman run collection.json -e env-staging.json
# 运行并生成 HTML 报告
newman run collection.json -e env-staging.json \
-r htmlextra \
--reporter-htmlextra-export reports/test-report.html
# 运行并输出 JSON 摘要
newman run collection.json -e env-staging.json \
-r json-summary \
--reporter-json-summary-export reports/summary.json
4.2 高级选项
# 设置超时、重试和并发
newman run collection.json -e env-staging.json \
--timeout-request 10000 \
--delay-request 500 \
--iteration-count 3 \
--bail \
--color on
五、定时自动化测试
# 创建测试脚本
cat > /opt/api-tests/run-tests.sh <<'EOF'
#!/bin/bash
cd /opt/api-tests
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
REPORT_DIR="reports/$TIMESTAMP"
mkdir -p "$REPORT_DIR"
newman run collection.json \
-e env-production.json \
-r htmlextra,cli \
--reporter-htmlextra-export "$REPORT_DIR/report.html" \
2>&1 | tee "$REPORT_DIR/output.log"
EXIT_CODE=$?
if [ $EXIT_CODE -ne 0 ]; then
echo "API 测试失败!退出码: $EXIT_CODE" | \
mail -s "API 测试告警" admin@example.com
fi
# 保留最近 30 天的报告
find reports/ -maxdepth 1 -type d -mtime +30 -exec rm -rf {} +
EOF
chmod +x /opt/api-tests/run-tests.sh
# 添加 crontab 定时任务(每小时执行一次)
echo "0 * * * * /opt/api-tests/run-tests.sh" | crontab -
六、Docker 化 Newman 运行
cat > docker-compose.yml <<'EOF'
version: '3.8'
services:
newman:
image: postman/newman:6-alpine
container_name: newman-runner
volumes:
- ./collection.json:/etc/newman/collection.json
- ./env-staging.json:/etc/newman/env-staging.json
- ./reports:/etc/newman/reports
command: >
run collection.json
-e env-staging.json
-r htmlextra,cli
--reporter-htmlextra-export reports/report.html
EOF
docker compose run --rm newman
七、CI/CD 集成示例
# GitHub Actions 示例
# .github/workflows/api-test.yml
name: API 自动化测试
on:
schedule:
- cron: '0 */6 * * *'
workflow_dispatch:
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- run: npm install -g newman newman-reporter-htmlextra
- run: newman run collection.json -e env-production.json -r htmlextra --reporter-htmlextra-export report.html
- uses: actions/upload-artifact@v4
if: always()
with:
name: test-report
path: report.html
八、常见问题
SSL 证书验证失败
# 跳过 SSL 验证(仅用于测试环境)
newman run collection.json -e env-staging.json --insecure
环境变量传递
# 通过命令行覆盖环境变量
newman run collection.json \
--env-var "baseUrl=http://localhost:3000" \
--env-var "authToken=test_token"
总结
Postman 和 Newman 组合提供了从手动调试到自动化测试的完整 API 测试方案。配合 Swagger 文档可以先定义接口再编写测试。如果需要 Webhook 回调测试,可以参考 Webhook 中继服务教程。选购搬瓦工 VPS 请参考 全部方案,购买时使用优惠码 NODESEEK2026 可享受 6.77% 的折扣,购买链接:bwh81.net。