在 CentOS 上实现 Postman 自动化测试
一 环境准备与安装
- 安装 Node.js 与 npm(Newman 依赖):执行命令:sudo yum install -y nodejs npm。
- 下载并解压 Postman Linux 版本(.tar.gz):示例命令:wget https://dl.pstmn.io/download/latest/linux64 -O postman.tar.gz,随后 sudo tar -xzf postman.tar.gz -C /opt。
- 创建软链接便于全局执行:sudo ln -s /opt/Postman/Postman /usr/bin/postman;也可按需将 /opt/Postman 加入 PATH。
- 可选:创建桌面启动器(GUI 环境)以便从应用菜单启动 Postman。以上步骤完成后即可在终端输入 postman 启动图形界面。
二 编写可自动化的测试脚本
- 在 Postman 中为请求或集合编写 Tests 脚本,常用断言示例:
- 状态码:pm.test(“Status code is 200”, () => pm.response.to.have.status(200));
- 响应时间:pm.test(“Response time < 500ms”, () => pm.expect(pm.response.responseTime).to.be.below(500));
- 响应头:pm.test(“Content-Type is JSON”, () => pm.response.to.have.header(“Content-Type”, /application/json/));
- 响应体字段:pm.test(“Has userId”, () => pm.expect(pm.response.json()).to.have.property(“userId”));
- 使用 Pre-request Script 动态准备数据,例如:pm.request.headers.add({ key: “Authorization”, value: "Bearer " + pm.environment.get(“token”) });
- 通过环境变量与集合变量实现链式调用与数据传递,例如:先保存 postId,再在后续请求中使用 {{postId}}。
三 数据驱动与集合运行
- 准备数据文件(CSV 或 JSON),例如 data.csv:
- 在集合运行器(Runner)中选择集合与数据文件,设置迭代次数与数据映射;在请求脚本中通过 pm.iterationData.get(“username”) 读取当前行数据,实现参数化与批量执行。
四 无头自动化与 CI 集成
- 安装 Newman:npm install -g newman。
- 基本运行:将集合与环境导出为 collection.json / environment.json,执行:newman run collection.json -e environment.json。
- 生成报告:安装 newman-reporter-html,执行:newman run collection.json -e environment.json -r html --reporter-html-export report.html。
- 无头与持续集成:在 Jenkins/GitLab CI 的无头环境(如 headless Chrome/无 GUI)中直接运行 Newman 命令;结合 git 拉取最新集合与环境,使用 cron 或流水线定时触发,失败即返回非零退出码以中断构建。
五 常见问题与实用建议
- 无头环境无法启动 GUI:Postman 桌面应用需 GUI,自动化请使用 Newman;若必须使用 GUI,可通过 Xvfb 虚拟显示运行 Postman(不推荐用于 CI)。
- 数据与机密管理:避免在代码中硬编码敏感信息,使用 Environment/Global 变量或 Secrets 管理;数据文件纳入版本控制时注意脱敏。
- 报告与可追溯:在 Newman 报告中记录 迭代数据、环境变量快照、响应时间,便于定位失败用例与回归分析。
- 依赖与版本:固定 Node.js / npm / Newman 版本,避免因升级导致命令或报告格式变化。