在 CentOS 上使用 Postman 进行接口测试
一 安装与启动
- 下载并解压
- 下载 Linux 版本压缩包:
- wget https://dl.pstmn.io/download/latest/linux64 -O postman.tar.gz
- 解压到系统目录(如 /opt):
- sudo mkdir -p /opt
- sudo tar -xzf postman.tar.gz -C /opt
- 创建软链接便于启动
- sudo ln -sfn /opt/Postman/Postman /usr/bin/postman
- 启动与桌面入口(可选)
- 启动:在终端输入:postman
- 创建桌面文件(GUI 环境):
- sudo tee /usr/share/applications/postman.desktop <<‘EOF’
[Desktop Entry]
Encoding=UTF-8
Name=Postman
Comment=API Development and Testing
Exec=/usr/bin/postman
Icon=/opt/Postman/app/resources/app/assets/icon.png
Terminal=false
Type=Application
Categories=Development;
EOF
- 若提示无 GUI,可忽略桌面入口,仅用命令行启动。
二 图形界面进行接口测试
- 创建请求
- 点击左上角 New → HTTP Request,选择方法(如 GET/POST),在 URL 输入接口地址。
- 设置请求头与请求体
- Headers:如 Content-Type: application/json
- Body:选择 raw → JSON,输入示例:
- { “name”: “John”, “email”: “john@example.com” }
- 发送请求与查看结果
- 点击 Send,在下方查看 Status、Headers、Body、Time 等信息。
- 组织与复用
- 新建 Collection 管理相关接口,便于批量运行与共享。
三 环境变量与自动化测试
- 环境变量
- 在侧边栏 Environments → New Environment 创建环境,添加变量如 base_url=https://api.example.com
- 在请求中使用 {{base_url}}/users 引用变量,便于在不同环境(开发/测试/生产)间切换。
- 断言与脚本
- Pre-request Script(请求前):
- pm.environment.set(“timestamp”, new Date().toISOString())
- Tests(请求后):
- 检查状态码:
- pm.test(“Status code is 200”, () => pm.response.to.have.status(200))
- 检查响应内容:
- pm.test(“Body contains success”, () => pm.expect(pm.response.text()).to.include(“成功”))
- 集合运行
- 在 Collection Runner 中批量运行请求,结合数据文件可实现参数化测试。
四 命令行自动化与 CI 集成
- 安装 Newman
- 需先安装 Node.js 与 npm(示例:sudo yum install -y nodejs npm)
- 全局安装 Newman:npm install -g newman
- 运行测试
- 导出集合与环境为 JSON(Collection → Export;Environment → Export)
- 运行命令:
- newman run collection.json -e environment.json
- 生成报告(可选)
- 安装报告插件:npm install -g newman-reporter-html
- 生成 HTML 报告:
- newman run collection.json -e environment.json -r html --reporter-html-export report.html
- CI/CD 集成
- 在 Jenkins/GitLab CI 等流水线中添加 Newman 执行步骤,实现提交或部署时自动运行接口测试。
五 常见问题与实用技巧
- 无图形界面如何测试
- 使用 Newman 在服务器上直接运行集合,适合无头环境(如纯 CLI 的 CentOS 服务器)。
- 快速复用请求
- 将请求导出为 cURL,便于在终端复用或分享给其他开发者。
- 变量与动态值
- 在 Pre-request Script 中生成 timestamp、nonce、token 等动态值,供后续请求使用。
- 接口依赖与 Mock
- 使用 Postman Mock Server 模拟下游接口,提升前后端并行开发效率。