温馨提示×

Linux Postman如何使用脚本自动化测试

小樊
54
2025-09-14 07:00:33
栏目: 智能运维

在Linux下使用Postman进行脚本自动化测试,可按以下步骤操作:

  1. 安装依赖工具

    • 安装Node.js和npm:
      sudo apt-get update && sudo apt-get install nodejs npm  
      
    • 安装Newman(命令行工具):
      npm install -g newman  
      
  2. 创建测试集合

    • 在Postman中创建API测试集合,定义请求、断言(如状态码、响应时间、JSON字段校验等),并保存为JSON文件(如my-api-tests.json)。
      • 示例断言脚本(在请求的“Tests”标签页编写):
        // 检查状态码  
        pm.test("Status code is 200", function() {  
          pm.response.to.have.status(200);  
        });  
        // 检查响应体包含特定字段  
        pm.test("Response has 'id' field", function() {  
          const jsonData = pm.response.json();  
          pm.expect(jsonData).to.have.property("id");  
        });  
        
  3. 编写运行脚本

    • 创建run-tests.js文件,调用Newman运行集合:
      const newman = require('newman');  
      newman.run({  
        collection: 'path/to/my-api-tests.json',  
        // 可选:指定环境变量文件  
        // environment: 'path/to/env.json',  
        reporters: 'cli', // 输出格式(cli/html/json/junit)  
      }, function(err, summary) {  
        if (err) console.error(err);  
        console.log(summary);  
      });  
      
  4. 执行测试

    • 在终端运行脚本:
      node run-tests.js  
      
  5. 集成到CI/CD(可选)

    • 在Jenkins、GitLab CI等工具中添加脚本步骤,通过Newman命令自动执行测试并生成报告(如HTML格式)。

说明

  • 测试脚本通过JavaScript编写,利用pm对象操作请求和响应。
  • 环境变量、数据驱动测试可通过pm.environmentpm.iterationData实现。
  • 报告生成支持多种格式,便于持续集成分析。

0