当前位置: 首页 > news >正文

Postman API 测试使用指南:从入门到精通

1. Postman 基础介绍

什么是 Postman?

Postman 是一个功能强大的 API 开发工具,提供:

  • API 测试:手动和自动化测试
  • API 开发:请求构建和调试
  • 文档生成:自动生成 API 文档
  • Mock 服务:模拟 API 响应
  • 监控:API 性能监控

Postman 核心概念

概念说明用途
Workspace工作空间团队协作环境
Collection集合组织相关 API 请求
Environment环境变量管理不同环境的配置
Request请求单个 API 调用
Script脚本自动化测试逻辑

2. Postman 安装与配置

安装方式

  1. 桌面应用(推荐):官网下载
  2. Web 版本:直接浏览器访问
  3. 命令行工具:Newman(用于 CI/CD)

初始配置

// 首次使用建议配置
1. 创建账号(同步数据)
2. 设置主题(Dark/Light)
3. 配置代理(如有需要)
4. 安装拦截器(浏览器扩展)

3. 创建第一个 API 测试

基础请求构建

步骤 1:创建新请求

1. 点击 "+" 号新建 Tab
2. 选择请求方法:GET/POST/PUT/DELETE
3. 输入请求 URL:https://api.example.com/users
4. 点击 "Send" 发送请求

步骤 2:查看响应

{"status": 200,"time": 245,"size": "1.2 KB","body": {"users": [{"id": 1,"name": "张三","email": "zhang@example.com"}]}
}

完整的请求示例

POST https://api.example.com/users
Content-Type: application/json
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5C...{"name": "李四","email": "li@example.com","password": "securepassword123"
}

4. 集合(Collection)管理

创建集合

1. 点击 "Collections" → "Create Collection"
2. 输入集合名称:用户管理 API
3. 添加描述:用户相关的所有 API 接口
4. 配置授权(可选)

集合结构设计示例

用户管理 API/
├── 认证相关/
│   ├── 用户登录 - POST /auth/login
│   ├── 刷新令牌 - POST /auth/refresh
│    └── 用户注销 - POST /auth/logout
├── 用户管理/
│   ├── 获取用户列表 - GET /users
│   ├── 创建用户 - POST /users
│   ├── 获取用户详情 - GET /users/:id
│   ├── 更新用户 - PUT /users/:id
│    └── 删除用户 - DELETE /users/:id
└── 测试工具/├── 清理测试数据 - POST /test/cleanup└── 生成测试数据 - POST /test/setup

集合级别配置

// 集合级别脚本(Pre-request Script)
console.log('集合请求开始时间:', new Date().toISOString());// 集合级别测试脚本(Tests)
pm.test("集合级测试: 响应时间检查", function () {pm.expect(pm.response.responseTime).to.be.below(1000);
});

5. 环境变量管理

创建环境变量

// 开发环境 (development)
base_url: https://dev-api.example.com
token: dev_token_123
user_id: 1001// 测试环境 (testing)
base_url: https://test-api.example.com
token: test_token_456
user_id: 2001// 生产环境 (production)
base_url: https://api.example.com
token: prod_token_789
user_id: 3001

变量使用语法

# 在 URL 中使用变量
GET {{base_url}}/users/{{user_id}}# 在 Header 中使用变量
Authorization: Bearer {{token}}# 在 Body 中使用变量
{"userId": {{user_id}},"environment": "{{env}}"
}

动态设置变量

// Pre-request Script: 请求前设置变量
pm.environment.set("timestamp", new Date().getTime());
pm.environment.set("random_email", `test${Math.random()}@example.com`);// Tests Script: 请求后设置变量
var jsonData = pm.response.json();
pm.environment.set("auth_token", jsonData.token);
pm.environment.set("user_id", jsonData.user.id);

6. 测试脚本编写详解

测试脚本结构

// 基本的测试结构
pm.test("测试描述", function () {// 断言逻辑pm.expect(true).to.be.true;
});// 响应状态码测试
pm.test("状态码为 200", function () {pm.response.to.have.status(200);
});pm.test("状态码为 201", function () {pm.response.to.have.status(201);
});

常用测试断言

响应状态测试
// 状态码验证
pm.test("成功状态码", function () {pm.expect(pm.response.code).to.be.oneOf([200, 201, 204]);
});pm.test("客户端错误", function () {pm.expect(pm.response.code).to.be.within(400, 499);
});
响应头测试
// 响应头验证
pm.test("Content-Type 头存在", function () {pm.response.to.have.header("Content-Type");
});pm.test("Content-Type 是 application/json", function () {pm.expect(pm.response.headers.get("Content-Type")).to.include("application/json");
});pm.test("缓存头设置正确", function () {pm.expect(pm.response.headers.get("Cache-Control")).to.include("no-cache");
});
响应体测试
// JSON 响应体验证
pm.test("响应包含用户信息", function () {var jsonData = pm.response.json();pm.expect(jsonData).to.have.property('user');pm.expect(jsonData.user).to.have.property('id');pm.expect(jsonData.user).to.have.property('name');pm.expect(jsonData.user).to.have.property('email');
});pm.test("用户 ID 是数字", function () {var jsonData = pm.response.json();pm.expect(jsonData.user.id).to.be.a('number');
});pm.test("邮箱格式正确", function () {var jsonData = pm.response.json();var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;pm.expect(emailRegex.test(jsonData.user.email)).to.be.true;
});
性能测试
// 响应时间测试
pm.test("响应时间小于 500ms", function () {pm.expect(pm.response.responseTime).to.be.below(500);
});pm.test("响应时间合理", function () {pm.expect(pm.response.responseTime).to.be.within(100, 1000);
});

复杂测试场景

数据验证测试
// 数组数据验证
pm.test("用户列表数据结构正确", function () {var jsonData = pm.response.json();// 验证是数组pm.expect(jsonData.users).to.be.an('array');// 验证数组不为空pm.expect(jsonData.users.length).to.be.above(0);// 验证每个用户对象的结构jsonData.users.forEach(function(user) {pm.expect(user).to.have.keys(['id', 'name', 'email', 'createdAt']);pm.expect(user.id).to.be.a('number');pm.expect(user.name).to.be.a('string').that.is.not.empty;});
});
业务逻辑测试
// 业务规则验证
pm.test("新创建用户状态为未激活", function () {var jsonData = pm.response.json();pm.expect(jsonData.user.status).to.equal('inactive');
});pm.test("创建时间应该在当前时间之前", function () {var jsonData = pm.response.json();var createdAt = new Date(jsonData.user.createdAt);var now = new Date();pm.expect(createdAt.getTime()).to.be.lessThan(now.getTime());
});pm.test("密码字段不应该返回", function () {var jsonData = pm.response.json();pm.expect(jsonData.user.password).to.be.undefined;
});

7. Pre-request Script 使用

请求前处理

// 生成动态数据
const timestamp = new Date().getTime();
pm.environment.set("unique_email", `test${timestamp}@example.com`);
pm.environment.set("random_id", Math.floor(Math.random() * 10000));// 计算签名(用于认证)
const crypto = require('crypto-js');
const secret = pm.environment.get("api_secret");
const payload = JSON.stringify(pm.request.body.raw);
const signature = crypto.HmacSHA256(payload, secret).toString();
pm.request.headers.add({key: 'X-Signature',value: signature
});// 条件逻辑
if (pm.environment.get("env") === "production") {pm.request.headers.add({key: 'X-Production',value: 'true'});
}

8. 工作流和自动化测试

请求执行顺序

// 在 Tests 中控制工作流
if (pm.response.code === 201) {// 只有创建成功才执行后续测试postman.setNextRequest("获取用户详情");
} else {postman.setNextRequest("错误处理测试");
}// 停止工作流
if (pm.response.code === 500) {console.log("服务器错误,停止测试");postman.setNextRequest(null);
}

批量运行集合

1. 打开集合 → 点击 "Run"
2. 选择环境:development
3. 设置迭代次数:3
4. 延迟设置:1000ms
5. 数据文件:导入 CSV/JSON 测试数据
6. 点击 "Run Collection"

9. 数据驱动测试

使用 CSV 数据文件

username,email,password,expected_status
john,john@example.com,pass123,201
jane,jane@example.com,pass456,201
,invalid@example.com,pass789,400
admin,admin@example.com,,400

在测试中使用数据变量

// 读取数据文件中的变量
var username = pm.iterationData.get("username");
var expectedStatus = parseInt(pm.iterationData.get("expected_status"));// 动态构建请求体
pm.request.body.raw = JSON.stringify({username: username,email: pm.iterationData.get("email"),password: pm.iterationData.get("password")
});// 验证预期结果
pm.test(`状态码应为 ${expectedStatus}`, function () {pm.response.to.have.status(expectedStatus);
});

10. 高级功能和集成

Newman - 命令行运行

# 安装 Newman
npm install -g newman# 运行集合
newman run my-collection.json \-e development-environment.json \-d test-data.csv \-r html,json \--reporter-html-export report.html# 带延迟的运行
newman run collection.json \--delay-request 1000 \--timeout-request 5000

CI/CD 集成示例

# GitHub Actions 配置
name: API Tests
on: [push, pull_request]jobs:api-tests:runs-on: ubuntu-lateststeps:- uses: actions/checkout@v3- name: Setup Node.jsuses: actions/setup-node@v3with:node-version: '16'- name: Install Newmanrun: npm install -g newman- name: Run API Testsrun: |newman run collection.json \-e env.json \--reporters cli,json \--reporter-json-export results.json- name: Publish Resultsuses: actions/upload-artifact@v3with:name: api-test-resultspath: results.json

Mock Server 创建

1. 创建 Mock Server
2. 定义示例响应
3. 生成 Mock URL
4. 在前端开发中使用

11. 测试报告和分析

查看测试结果

// 测试结果统计
console.log("通过测试数:", pm.info.iteration);
console.log("失败测试数:", pm.info.failedRequests);// 性能指标
console.log("平均响应时间:", pm.info.meanTime);
console.log("最小响应时间:", pm.info.minTime);
console.log("最大响应时间:", pm.info.maxTime);

生成 HTML 报告

# 安装 HTML 报告器
npm install -g newman-reporter-html# 生成报告
newman run collection.json -r html --reporter-html-export report.html

12. 最佳实践和技巧

组织最佳实践

// 1. 使用描述性的测试名称
pm.test("用户注册 - 有效数据应返回201状态码", function() {});// 2. 模块化测试脚本
function validateUserStructure(user) {pm.expect(user).to.have.keys(['id', 'name', 'email']);pm.expect(user.id).to.be.a('number');pm.expect(user.name).to.be.a('string');
}// 3. 错误处理
try {var jsonData = pm.response.json();// 正常测试逻辑
} catch (e) {pm.test("响应应该是有效的JSON", function() {pm.expect.fail("无效的JSON响应: " + e.message);});
}

调试技巧

// 调试输出
console.log("请求URL:", pm.request.url.toString());
console.log("请求头:", JSON.stringify(pm.request.headers));
console.log("响应状态:", pm.response.code);
console.log("响应体:", pm.response.text());// 条件调试
if (pm.response.code !== 200) {console.log("异常响应:", pm.response.text());
}

13. 常见问题解决

问题 1:SSL 证书错误

解决方案:
1. Settings → General → SSL certificate verification → OFF
2. 或配置正确的证书

问题 2:CORS 错误

解决方案:
1. 安装 Postman 拦截器
2. 或使用代理设置

问题 3:变量不生效

// 检查变量作用域
console.log("环境变量:", pm.environment.toObject());
console.log("全局变量:", pm.globals.toObject());
console.log("集合变量:", pm.collectionVariables.toObject());

14. 学习资源

官方资源

  • Postman 学习中心
  • API 文档

通过本指南,你可以系统掌握 Postman 进行 API 测试的全流程。建议从简单的单个请求开始,逐步扩展到复杂的集合和自动化测试。实践是最好的学习方式!

http://www.dtcms.com/a/469235.html

相关文章:

  • VisualSVN-Server-2.5.26 TortoiseSVN-1.7.21
  • SVN 检出操作
  • 深度相机初探:立体视觉(Stereo Vision)、结构光(Structured Light)、TOF(Time of Flight,飞行时间)
  • SVN 生命周期
  • 武昌做网站公司互联网营销顾问是做什么的
  • 辉视融合服务器:强劲驱动电视信息发布,直播点播流畅运行,赋能高效传播
  • MyBatis-Spring-Boot快速上手指南
  • Linux运维实战:系统及服务管理(视频教程)
  • 服务器运维(四)服务器漏洞扫描工具与审查——东方仙化神期
  • SolidWorks服务器多人使用方案
  • 安卓手机app开发软件下载网站关键词优化效果
  • Redis中的RPOP、BRPOP、LPOP 和 BLPOP
  • R语言学习
  • 【C++】C++11 新特性详解(下)
  • 成都市公园城市建设管理局网站济南百度推广开户
  • 网站的技术建设公司网站建设 wordpress
  • 联想小新平板Pro GT/Y700四代平板无需解锁BL获取root权限方法
  • Linux系统安装PGSQL实现向量存储
  • 跨语言协作新范式:阿里云Qwen-MT与DooTask的翻译技术突破
  • LLM 笔记 —— 04 为什么语言模型用文字接龙,图片模型不用像素接龙呢?
  • ubuntu-20.04.6升级OpenSSH_10.2p1
  • redis lua脚本(go)调用教程以及debug调试
  • shopnc本地生活o2o网站源码有声小说网站开发
  • OpenHarmony 之Telephony电话服务技术详解:架构设计与Modem厂商库集成机制
  • 医疗AI记忆系统的分层存储机制:长期病史与短期会诊记忆的编程实现(代码部分)
  • Vue 基础认知全解析:从版本演进到生态定位
  • 苏州建网站的公司平台收费标准wordpress客户端源码分析
  • VibeCut - 智能剪辑探索与实现
  • Linux5:Linux网络编程
  • 大模型为什么会表现出逻辑性推理