Linux 下 Postman 测试脚本编写指南
一 环境与基本概念
二 编写第一个测试脚本
// 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());
三 常用断言与技巧
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"));
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"));
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: [] });
});
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 集成
npm install -g newmannewman run collection.jsonnewman run collection.json -e environment.jsonnewman run collection.json -e environment.json --reporters html --reporter-html-export report.html// 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
五 排错与最佳实践
console.log/info/warn/error,定位变量、响应与流程问题。pm.test 之外。tests[...] = ... 写法,统一采用 pm.test + pm.expect 的可读断言风格。