温馨提示×

Postman在Ubuntu上的自动化测试实践

小樊
57
2025-08-09 05:58:42
栏目: 智能运维

以下是在Ubuntu上进行Postman自动化测试的实践步骤:

一、安装Postman

  • 使用Snap安装
    sudo snap install postman --classic
    
  • 使用APT安装
    wget -qO - https://dl.postman.co/postman.gpg | sudo apt-key add -
    echo "deb https://dl.postman.co/debian $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/postman.list
    sudo apt update && sudo apt install postman
    

二、编写测试脚本

  • 基础断言:在请求的“Tests”标签页使用JavaScript编写断言,例如:
    // 验证状态码为200
    pm.test("Status code is 200", function () {
      pm.response.to.have.status(200);
    });
    // 验证响应体包含特定字段
    pm.test("Response has required fields", function () {
      const jsonData = pm.response.json();
      pm.expect(jsonData).to.have.property("id");
    });
    
  • 环境变量:在“Manage Environments”中创建变量(如api_url),在请求中使用{{api_url}}引用。

三、运行自动化测试

  • 命令行工具Newman
    1. 安装Newman:
      npm install -g newman
      
    2. 导出Postman集合为JSON文件,运行测试:
      newman run /path/to/collection.json -e /path/to/environment.json --reporters cli,html --reporter-html-export ./report.html
      
    3. 常用参数:
      • -e:指定环境文件
      • -r:指定报告格式(如clihtml

四、集成CI/CD

  • GitHub Actions示例
    1. 在仓库中创建.github/workflows/postman.yml
      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
      
    2. 提交代码后,GitHub Actions会自动执行测试并生成报告。

五、进阶技巧

  • 数据驱动测试:通过CSV/JSON文件导入测试数据,在请求中使用pm.iterationData.get("变量名")引用。
  • 测试报告:使用newman-reporter-htmlextra生成可视化HTML报告,或集成Allure生成专业报告。
  • Mock服务:在Postman中创建Mock服务器模拟API响应,用于离线测试。

0