阅读量:3
Linux 下 Postman 测试脚本编写指南
一 环境与基本概念
- 在 Linux 上,Postman 桌面客户端与 Windows/macOS 一致,测试脚本使用 JavaScript(Chai BDD 断言) 编写,运行在请求收到响应之后。脚本可添加到 请求、文件夹、集合 三个层级;执行顺序为:集合级脚本 → 文件夹级脚本 → 请求级脚本。在响应面板可查看 Test Results 与日志输出。
二 编写第一个测试脚本
- 新建请求(如 GET/POST),在右侧切换到 Tests 标签,输入以下示例并点击 Send:
// 1) 状态码
pm.test("Status code is 200", () => {
pm.response.to.have.status(200);
});
// 2) 响应时间
pm.test("Response time is less than 200ms", () => {
pm.expect(pm.response.responseTime).to.be.below(200);
});
// 3) JSON 取值并写入环境变量
pm.test("Extract token and set env", () => {
const jsonData = pm.response.json();
pm.expect(jsonData).to.have.property("token");
pm.environment.set("authToken", jsonData.token);
});
// 4) 在后续请求中使用变量(示例:设置请求头)
pm.request.headers.add({
key: "Authorization",
value: `Bearer ${pm.environment.get("authToken")}`
});
// 5) 控制台日志(View → Show Postman Console,快捷键:Ctrl+Alt+C)
console.log("URL:", pm.request.url.toString());
- 运行后在响应下方的 Test Results 查看通过/失败;如需调试,打开 Postman Console 查看日志。
三 常用断言与技巧
- 状态码与状态文本
pm.test("Status code is 201", () => pm.response.to.have.status(201));
pm.test("Successful POST", () => pm.expect(pm.response.code).to.be.oneOf([201, 202]));
pm.test("Status text is Created", () => pm.response.to.have.status("Created"));
- 响应头与 Cookie
pm.test("Content-Type is application/json", () => {
pm.expect(pm.response.headers.get("Content-Type")).to.eql("application/json");
});
pm.test("Cookie JSESSIONID exists", () => pm.cookies.has("JSESSIONID"));
- 响应体内容(JSON、文本包含、精确匹配)
const json = pm.response.json();
pm.test("Name is Jane", () => pm.expect(json.name).to.eql("Jane"));
pm.test("Body contains customer_id", () => {
pm.expect(pm.response.text()).to.include("customer_id");
});
pm.test("Body equals exact string", () => {
pm.response.to.have.body("whole-body-text");
});
- 数组与对象
pm.test("Errors array is empty", () => pm.expect(json.errors).to.be.empty);
pm.test("Areas includes goods", () => pm.expect(json.areas).to.include("goods"));
pm.test("Deeply includes object", () => {
pm.expect(json).to.deep.include({ created: true, errors: [] });
});
- JSON Schema 校验
const schema = { properties: { alpha: { type: "boolean" } } };
pm.test("Schema is valid", () => pm.response.to.have.jsonSchema(schema));
- 异步请求与调试
pm.sendRequest("https://postman-echo.com/get", (err, res) => {
console.log(res.json());
});
- 变量作用域与设置
pm.environment.set("key", "value"); // 环境变量(跨请求)
pm.globals.set("key", "value"); // 全局变量(全局共享)
pm.collectionVariables.set("key", "v"); // 集合变量(集合内共享)
- 旧语法提示:形如
tests["Body contains user_id"] = true;的写法已弃用,请使用pm.test+pm.expect。
四 批量运行与 CI 集成
- 使用 Newman(Postman 命令行工具)在 Linux 终端批量运行:
- 安装 Newman:
npm install -g newman - 在 Postman 中导出 集合 与 环境 为 JSON
- 基本运行:
newman run collection.json - 指定环境:
newman run collection.json -e environment.json - 生成 HTML 报告:
newman run collection.json -e environment.json --reporters html --reporter-html-export report.html - 也可在 Node.js 中驱动 Newman 运行并获取汇总
- 安装 Newman:
// run_tests.js
const newman = require('newman');
newman.run({
collection: './my_api_tests.json',
environment: './environment.json'
}, function (err, summary) {
if (err) { console.error(err); return; }
console.log(summary);
});
// 终端:node run_tests.js
- 在 Jenkins/GitLab CI 等 CI/CD 中将上述命令作为步骤执行,实现提交/部署时自动回归测试。
五 排错与最佳实践
- 使用 Postman Console(快捷键 Ctrl+Alt+C)输出
console.log/info/warn/error,定位变量、响应与流程问题。 - 注意变量作用域与声明位置,避免跨测试访问未定义变量;必要时将解析逻辑提升到所有
pm.test之外。 - 避免已弃用的
tests[...] = ...写法,统一采用pm.test+pm.expect的可读断言风格。 - 在集合/文件夹级编写公共初始化与清理脚本(如登录获取 token、登出清理),在请求级专注业务断言,提升复用性与维护性。
以上就是关于“Linux Postman如何编写测试脚本”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm