ubuntu

Ubuntu下Postman怎样使用脚本

小樊
33
2025-12-27 23:33:51
栏目: 智能运维

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");
});

四 运行与自动化

name: Postman Automation Test
on: [push, pull_request]
jobs:
  run-tests:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Install Newman
        run: npm install -g newman
      - name: Run Postman Collection
        run: newman run ./collections/api-tests.json -e ./environments/test-env.json --reporters cli,html

上述流程支持本地 Runner 与 CI/CD 的批量执行与报告生成。

五 最佳实践与排错

0
看了该问题的人还看了