温馨提示×

Postman在Ubuntu上如何实现自动化测试

小樊
51
2025-10-18 07:14:56
栏目: 智能运维

1. 在Ubuntu上安装Postman
Postman支持多种方式在Ubuntu上安装,常见方法如下:

  • Snap包管理器(推荐):打开终端,依次执行sudo snap install postman --classic,等待安装完成即可。
  • APT包管理器
    ① 导入Postman的GPG密钥:wget -qO - https://dl.postman.co/postman.gpg | sudo apt-key add -
    ② 添加Postman的APT仓库: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
  • Flatpak:若未安装Flatpak,先执行sudo apt update && sudo apt install flatpak;再添加Flathub仓库:flatpak remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo;最后安装Postman:flatpak install flathub com.postman.Postman

2. 准备自动化测试的基础框架

  • 创建集合(Collection):集合是组织测试用例的容器,点击Postman左侧“Collections”→右上角“New Collection”,输入名称(如“API_Automation”)并保存。可将相关请求拖入集合中,形成完整的测试流程。
  • 编写测试脚本
    • Tests脚本(响应后执行):在请求的“Tests”标签页中编写JavaScript断言,验证响应状态、响应体等内容。常见示例:
      // 检查状态码是否为200
      pm.test("Status code is 200", function () {
          pm.response.to.have.status(200);
      });
      // 检查响应体是否包含特定字段
      pm.test("Response contains user ID", function () {
          const jsonData = pm.response.json();
          pm.expect(jsonData).to.have.property("id");
      });
      
    • Pre-request Script(请求前执行):用于设置请求头、获取环境变量或生成动态数据。示例:
      // 从环境变量获取token并设置请求头
      const token = pm.environment.get("auth_token");
      pm.request.headers.add({ key: "Authorization", value: `Bearer ${token}` });
      
  • 配置环境变量:点击Postman右上角齿轮图标→“Manage Environments”→“Add”,输入环境名称(如“Test_Env”),添加变量(如base_url: https://api.example.com)。在请求中使用{{base_url}}引用变量,切换环境时变量值会自动替换。

3. 运行自动化测试

  • 使用Postman Runner
    ① 点击集合右侧“···”→“Run collection”;
    ② 在“Collection Runner”中选择目标集合、迭代次数(如10次)、环境变量(如“Test_Env”);
    ③ 点击“Run”,查看结果面板中的通过/失败用例数、响应时间、断言详情。
  • 命令行运行(Newman)
    Newman是Postman的命令行工具,需先安装Node.js(curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -sudo apt install -y nodejs),再执行npm install -g newman安装Newman。导出集合为JSON文件(点击集合→“Export”→选择“Collection v2.1”),然后运行:newman run /path/to/collection.json --environment /path/to/environment.json。可通过--reporters cli,json生成报告,或集成到Jenkins、GitLab CI等工具中。

4. 高级技巧提升测试效率

  • 数据驱动测试:准备CSV/JSON文件(如data.csvuserId,title\n1,Test User),在Collection Runner中勾选“Data”→选择文件。在脚本中使用pm.iterationData.get("userId")获取当前迭代数据,验证不同输入下的响应。
  • 测试用例组织:将集合按功能模块划分(如“User_Login”“Product_API”),使用文件夹分类请求。添加描述(如“测试用户登录接口的合法性”),便于团队协作。
  • CI/CD集成:在Jenkins中创建流水线,添加“Execute shell”步骤执行Newman命令;或在GitLab CI的.gitlab-ci.yml中添加:
    stages:
      - test
    run_postman_tests:
      stage: test
      script:
        - npm install -g newman
        - newman run /path/to/collection.json
    
    实现代码提交后自动运行测试。

0