Ubuntu 下 Postman 自动化脚本生成与落地
一 核心概念与脚本类型
二 在 Postman 内快速生成脚本
// Pre-request Script
const token = pm.environment.get("token");
pm.request.headers.add({ key: "Authorization", value: "Bearer " + token });
// Tests
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));
// Tests
const jsonData = pm.response.json();
pm.test("User ID present", () => pm.expect(jsonData.id).to.be.a("number"));
三 数据驱动与动态值
四 命令行自动化与 CI 集成
npm install -g newman
newman run collection.json --environment environment.json
五 实战模板 注册登录并串联请求
// 注册:生成随机邮箱并注册
pm.test("Register user", () => {
const email = `user${Math.floor(Math.random()*10000)}@example.com`;
const password = "password123";
pm.sendRequest({
url: pm.environment.get("apiBaseUrl") + "/register",
method: "POST",
body: JSON.stringify({ email, password }),
headers: { "Content-Type": "application/json" }
}, (err, res) => {
pm.expect(res.status).to.eql(200);
pm.expect(res.json().email).to.eql(email);
});
});
// 登录:获取 token 并写入环境变量
pm.test("Login and set authToken", () => {
const email = pm.environment.get("lastRegisteredEmail") || `user${Math.floor(Math.random()*10000)}@example.com`;
const password = "password123";
pm.sendRequest({
url: pm.environment.get("apiBaseUrl") + "/login",
method: "POST",
body: JSON.stringify({ email, password }),
headers: { "Content-Type": "application/json" }
}, (err, res) => {
pm.expect(res.status).to.eql(200);
const token = res.json().token;
pm.expect(token).to.be.a("string").and.not.empty;
pm.environment.set("authToken", token);
});
});
// 获取用户信息:使用 token 访问受保护接口
pm.test("Get user info", () => {
const token = pm.environment.get("authToken");
pm.sendRequest({
url: pm.environment.get("apiBaseUrl") + "/user",
method: "GET",
headers: { "Authorization": `Bearer ${token}` }
}, (err, res) => {
pm.expect(res.status).to.eql(200);
pm.expect(res.json()).to.have.property("email");
});
});