Ubuntu下Postman脚本编写与执行技巧
一 环境准备与安装
二 脚本编写核心要点
三 快速示例可复用模板
// 从环境读取
const token = pm.environment.get("token") || "";
const userId = pm.collectionVariables.get("userId");
// 设置请求头
pm.request.headers.add({ key: "Authorization", value: "Bearer " + token });
// 动态查询参数
if (userId) {
pm.request.url.query.add({ key: "userId", value: userId });
}
console.log("Pre-request: token=", token, "userId=", userId);
// 状态码
pm.test("Status code is 200", () => {
pm.response.to.have.status(200);
});
// 响应时间
pm.test("Response time < 200ms", () => {
pm.expect(pm.response.responseTime).to.be.below(200);
});
// JSON 结构与字段
pm.test("Response has userId and is string", () => {
const json = pm.response.json();
pm.expect(json).to.have.property("userId").that.is.a("string");
});
四 执行与自动化
五 调试与最佳实践