Postman在CentOS上如何进行数据验证
导读:在 CentOS 上使用 Postman 进行数据验证 一 核心思路与适用场景 在 CentOS 桌面环境使用 Postman 或在服务器上配合 Newman 运行集合,验证思路完全一致:在请求的 Tests 选项卡用 JavaScrip...
在 CentOS 上使用 Postman 进行数据验证
一 核心思路与适用场景
- 在 CentOS 桌面环境使用 Postman 或在服务器上配合 Newman 运行集合,验证思路完全一致:在请求的 Tests 选项卡用 JavaScript 编写断言,请求发送后自动执行,结果在 Test Results 面板展示。常用断言涵盖 状态码、响应体内容、响应时间、JSON 字段值、响应头、以及 XML 转 JSON 等。Postman 5.0+ 推荐使用 pm.test / pm.expect 风格,更易读、可组合。
二 常用验证与示例脚本
- 状态码与状态名
pm.test("Status code is 200", () => pm.response.to.have.status(200)); pm.test("Status name contains Created", () => pm.response.to.have.status("Created")); - 响应时间与内容包含
pm.test("Response time < 200ms", () => pm.expect(pm.response.responseTime).to.be.below(200)); pm.test("Body contains keyword", () => pm.expect(pm.response.text()).to.include("keyword")); - JSON 字段与结构
const json = pm.response.json(); pm.test("id equals 100", () => pm.expect(json.id).to.eql(100)); pm.test("has email", () => pm.expect(json).to.have.property("email")); pm.test("items length is 5", () => pm.expect(json.items).to.have.lengthOf(5)); - 响应头与精确文本
pm.test("Content-Type is application/json", () => { pm.expect(pm.response.headers.get("Content-Type")).to.include("application/json"); } ); pm.test("Exact body match", () => pm.response.to.have.body("exact string")); - XML 响应处理
const json = xml2Json(pm.response.text()); pm.test("XML converted and has key", () => pm.expect(json).to.have.property("key")); - 变量提取与链路
const json = pm.response.json(); pm.environment.set("userId", json.id); // 供后续请求使用 { { userId} } - 旧式写法兼容(不推荐新写,但旧脚本常见)
tests["Status code is 200"] = responseCode.code === 200; tests["Body matches string"] = responseBody.has("keyword"); tests["Response time < 200ms"] = responseTime < 200; var data = JSON.parse(responseBody); tests["Value equals 100"] = data.value === 100;
以上写法适用于 Postman 与 Newman,在 CentOS 环境下一致生效。
三 在 CentOS 上的运行方式
- 图形界面
- 下载并解压 Postman 到 /opt,创建软链便于启动:
sudo ln -s /opt/Postman/Postman /usr/bin/postman,之后直接运行postman打开 GUI,在 Tests 编写脚本、在 Test Results 查看结果。
- 下载并解压 Postman 到 /opt,创建软链便于启动:
- 命令行自动化
- 安装 Node.js/npm 后安装 Newman:
npm i -g newman - 导出集合与环境为 collection.json / environment.json
- 运行并生成报告:
newman run collection.json -e environment.json -r cli,html,json - 适合在 CentOS 服务器做批量回归、CI/CD 集成与定时任务。
- 安装 Node.js/npm 后安装 Newman:
四 调试与最佳实践
- 使用 console.log / console.info 输出调试信息,在 Postman 控制台查看;脚本报错会在编辑器与结果面板标红,便于定位。
- 避免用
responseBody.has("success")这类“模糊匹配”去判断业务字段,优先解析为 JSON 后精确断言,例如:pm.expect(json.code).to.eql("success")。 - 合理使用变量作用域:环境变量 优先于 全局变量,在 URL、Header、Body 中以 { { 变量名} } 引用,便于多环境复用。
- 使用 pm.test / pm.expect 组织测试,语义清晰、可组合,并充分利用编辑器右侧的 代码片段模板 快速生成常用断言。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: Postman在CentOS上如何进行数据验证
本文地址: https://pptw.com/jishu/772037.html
