在 CentOS 上使用 Postman 进行数据验证
一 核心思路与适用场景
二 常用验证与示例脚本
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"));
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"));
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 上的运行方式
sudo ln -s /opt/Postman/Postman /usr/bin/postman,之后直接运行 postman 打开 GUI,在 Tests 编写脚本、在 Test Results 查看结果。npm i -g newmannewman run collection.json -e environment.json -r cli,html,json
四 调试与最佳实践
responseBody.has("success") 这类“模糊匹配”去判断业务字段,优先解析为 JSON 后精确断言,例如:pm.expect(json.code).to.eql("success")。