Ubuntu下使用 Postman 与 Newman 的自动化测试实践
一 安装与环境准备
- 安装 Postman(任选其一)
- Snap:sudo snap install postman --classic
- APT 仓库:导入 GPG 并添加源后安装
- wget -qO - https://dl.postman.co/postman.gpg | sudo apt-key add -
- echo “deb https://dl.postman.co/debian $(lsb_release -cs) main” | sudo tee /etc/apt/sources.list.d/postman.list
- sudo apt update && sudo apt install postman
- 手动安装:下载 Linux 包、解压并创建启动器
- wget https://dl.pstmn.io/download/latest/linux-x64 -O postman.tar.gz
- sudo tar -xzf postman.tar.gz -C /opt/
- sudo ln -s /opt/Postman/Postman /usr/local/bin/postman
- 创建 /usr/share/applications/postman.desktop(Exec 指向 /opt/Postman/Postman/Postman,Icon 指向对应图标),保存后可用应用菜单或命令行 postman 启动。
- 安装 Newman(Postman 命令行运行器)
- npm install -g newman,安装后用 newman -h 验证。
二 在 Postman 中编写自动化测试
- 创建请求与集合
- 新建请求(如 GET/POST),填写 URL/Headers/Body,保存到 Collection,便于批量运行与维护。
- Pre-request Script(请求前脚本)
- 常用于动态设置变量、签名、时间戳等,例如读取环境变量并注入 Authorization 头:
- const token = pm.environment.get(“token”);
- pm.request.headers.add({ key: “Authorization”, value: "Bearer " + token });
- Tests(请求后脚本)
- 使用 pm.test 与 Chai 断言验证响应,例如:
- 状态码:pm.test(“状态码为200”, () => pm.response.to.have.status(200));
- 响应时间:pm.test(“响应时间小于200ms”, () => pm.expect(pm.response.responseTime).to.be.below(200));
- 响应体字段:const json = pm.response.json(); pm.expect(json.name).to.eql(“test_user”);
- 变量与环境
- 在环境/全局中定义 baseUrl、token 等,请求中以 {{baseUrl}} 引用,便于在 开发/测试/生产 环境间切换。
三 本地运行与调试
- 集合运行器 Runner
- 在 Postman 中点击 Runner,选择集合与 Environment,可配置 迭代次数、延迟、数据文件 等,批量执行并查看每个请求的 断言结果 与 响应日志。
- 控制台与日志
- 使用 console.log 输出调试信息,结合 Postman 控制台查看脚本执行过程与错误堆栈,快速定位问题。
四 在 CI/CD 中自动化执行
- 导出资产
- 将 Collection 导出为 JSON,并导出或维护 Environment JSON 文件,以便在无界面环境运行。
- 命令行执行与报告
- 基本运行:newman run my-collection.json -e my-env.json
- HTML 报告:newman run my-collection.json -e my-env.json --reporters html --reporter-html-export report.html
- JUnit 报告(便于 Jenkins 等):newman run my-collection.json --reporters cli,junit --reporter-junit-export report.xml
- GitHub Actions 示例
- 在仓库 .github/workflows/postman.yml 中配置:
- 触发分支:push / pull_request on main
- 步骤:安装 Node.js、全局安装 newman、运行集合并导出 JUnit 报告、上传报告产物
- 参考命令:
- npm install -g newman
- newman run “your_postman_collection.json” --reporters cli,junit --reporter-junit-export report.xml
- 使用 actions/upload-artifact 上传 report.xml 供后续查看或质量门禁使用。
五 常见问题与实用建议
- 环境与变量优先级:合理使用 Environment/Global/Collection/Data 变量,避免硬编码;在 Pre-request 中动态生成并注入必要参数(如 nonce、timestamp、signature)。
- 数据与数据驱动:结合 CSV/JSON 数据文件 做参数化测试,覆盖多组输入与边界场景。
- 报告与质量门禁:在 CI 中使用 JUnit/HTML 报告,结合阈值或失败条件实现质量门禁(如 newman 非0退出码即失败)。
- 稳定性与幂等:对可能产生副作用的接口使用 测试专用账号/测试数据,或在 Pre-request 中做幂等准备(如清理、重置状态)。
- 调试技巧:在关键步骤 console.log 输出上下文;必要时拆分集合、降低并发,定位偶发问题。