Postman高级技巧揭秘 – 从接口测试到自动化Mock服务搭建

前言

大家好,我是QA攻城狮,做接口测试6年了。Postman是我最常用的工具,很多测试同行用它发请求、看响应,但这只是Postman的基础功能。今天分享一些Postman的高级技巧,让你的接口测试更专业。

这篇文章会覆盖:

一、变量管理

变量类型

Postman有5种变量,作用域从小到大:

变量类型 作用域 用途
Local变量 单次请求 临时数据
Data变量 Collection Runner 批量测试数据
Environment变量 环境 环境配置
Collection变量 Collection 共享配置
Global变量 全局 跨环境数据

环境变量

javascript
// 设置环境变量
pm.environment.set(“base_url”, “https://api.test.com”);
pm.environment.set(“token”, “Bearer abc123”);

// 获取环境变量
const baseUrl = pm.environment.get(“base_url”);
const token = pm.environment.get(“token”);

// 删除环境变量
pm.environment.unset(“token”);

// 清空所有环境变量
pm.environment.clear();

在请求中使用:

{{base_url}}/users/{{user_id}}

全局变量

javascript
// 设置全局变量
pm.globals.set(“version”, “v1”);

// 获取全局变量
pm.globals.get(“version”);

Collection变量

在Collection设置中添加:

javascript
// 使用Collection变量
const retry = pm.collectionVariables.get(“retry_count”);

动态变量

Postman内置动态变量:


{{$timestamp}} // 当前时间戳
{{$randomInt}} // 随机整数
{{$randomEmail}} // 随机邮箱
{{$guid}} // UUID
{{$date}} // 当前日期
{{$isoDate}} // ISO格式日期

示例:
json
{
“email”: “{{$randomEmail}}”,
“id”: “{{$guid}}”,
“timestamp”: “{{$timestamp}}”
}

二、脚本编写

Pre-request Script(请求前脚本)

在发送请求前执行的脚本,用于:

javascript
// Pre-request Script示例

// 生成时间戳
const timestamp = Date.now();
pm.environment.set(“timestamp”, timestamp);

// 计算签名(示例)
const secret = pm.environment.get(“secret”);
const params = timestamp=${timestamp}&secret=${secret};
const sign = CryptoJS.MD5(params).toString();
pm.environment.set(“sign”, sign);

// 设置动态请求头
pm.request.headers.add({
key: “X-Signature”,
value: sign
});

// 发送前置请求(获取Token)
pm.sendRequest({
url: pm.environment.get(“base_url”) + “/auth/token”,
method: “POST”,
header: {“Content-Type”: “application/json”},
body: {
mode: “raw”,
raw: JSON.stringify({
username: “test”,
password: “test123”
})
}
}, function(err, res) {
if (!err) {
const token = res.json().access_token;
pm.environment.set(“auth_token”, token);
}
});

Tests Script(测试脚本)

在收到响应后执行的脚本,用于:

javascript
// Tests Script示例

// 基础断言
pm.test(“状态码为200”, function() {
pm.response.to.have.status(200);
});

pm.test(“响应时间小于500ms”, function() {
pm.expect(pm.response.responseTime).to.be.below(500);
});

pm.test(“响应包含data字段”, function() {
pm.response.to.have.jsonBody(“data”);
});

// JSON数据验证
const jsonData = pm.response.json();

pm.test(“用户列表不为空”, function() {
pm.expect(jsonData.data.length).to.be.above(0);
});

pm.test(“用户ID为正整数”, function() {
jsonData.data.forEach(user =

{

pm.expect(user.id).to.be.a(“number”).and.to.be.above(0);
});
});

pm.test(“响应结构正确”, function() {
pm.expect(jsonData).to.have.property(“code”);
pm.expect(jsonData).to.have.property(“message”);
pm.expect(jsonData).to.have.property(“data”);
});

// 提取响应数据
const userId = jsonData.data[0].id;
pm.environment.set(“user_id”, userId);

// 保存响应到文件(Collection Runner)
pm.collectionVariables.set(“last_response”, pm.response.text());

常用断言方法

javascript
// 状态码断言
pm.test(“状态码为200”, () =

{

pm.response.to.have.status(200);
});

pm.test(“状态码为2xx”, () =

{

pm.response.to.be.success;
});

pm.test(“状态码为4xx”, () =

{

pm.response.to.be.clientError;
});

// 响应体断言
pm.test(“响应体不为空”, () =

{

pm.response.to.not.be.empty;
});

pm.test(“响应为JSON”, () =

{

pm.response.to.be.json;
});

// JSON字段断言
pm.test(“包含token字段”, () =

{

pm.response.to.have.jsonBody(“token”);
});

pm.test(“token不为空”, () =

{

const json = pm.response.json();
pm.expect(json.token).to.not.be.null;
});

// 响应头断言
pm.test(“包含Content-Type”, () =

{

pm.response.to.have.header(“Content-Type”);
});

pm.test(“Content-Type为JSON”, () =

{

pm.response.headers.get(“Content-Type”).includes(“application/json”);
});

三、Mock Server搭建

为什么需要Mock

接口测试场景:

创建Mock Server

1. 创建Mock Collection

在Postman中:

2. 定义Mock响应

在请求的 Examples 中添加响应示例:

json
// 成功响应示例
{
“code”: 200,
“message”: “success”,
“data”: {
“users”: [
{“id”: 1, “name”: “张三”},
{“id”: 2, “name”: “李四”}
]
}
}

// 错误响应示例
{
“code”: 404,
“message”: “用户不存在”,
“data”: null
}

3. 配置Mock环境

javascript
// Mock环境变量
{
“mock_url”: “https://mock.postman.com/my-mock”
}

Mock Server实战

javascript
// Pre-request Script:根据场景选择Mock响应
const testScenario = pm.environment.get(“scenario”);

if (testScenario === “success”) {
pm.request.url = pm.environment.get(“mock_url”) + “/success”;
} else if (testScenario === “error”) {
pm.request.url = pm.environment.get(“mock_url”) + “/error”;
}

Mock数据生成

javascript
// 动态生成Mock数据
function generateMockUser(id) {
return {
id: id,
name: 用户${id},
email: user${id}@test.com,
phone: 1380000000${id},
createTime: new Date().toISOString()
};
}

// Mock响应示例
const mockData = {
code: 200,
message: “success”,
data: {
users: Array.from({length: 10}, (_, i) =

generateMockUser(i + 1)),

total: 10,
page: 1,
pageSize: 10
}
};

四、Collection Runner批量测试

运行Collection

在Postman界面:
1. 点击Collection –

Run
2. 选择要运行的请求
3. 设置运行参数

配置运行参数

测试数据文件

CSV格式:

username,password,expected_status
testuser,password123,200
wronguser,wrongpass,401
emptyuser,,400

JSON格式:
json
[
{“username”: “testuser”, “password”: “password123”, “expected_status”: 200},
{“username”: “wronguser”, “password”: “wrongpass”, “expected_status”: 401}
]

使用测试数据

javascript
// Tests Script中使用数据变量
const expectedStatus = pm.iterationData.get(“expected_status”);

pm.test(“状态码验证”, function() {
pm.response.to.have.status(expectedStatus);
});

五、Newman命令行运行

安装Newman

bash
npm install -g newman

基础命令

bash

运行Collection

newman run collection.json

指定环境

newman run collection.json -e environment.json

指定全局变量

newman run collection.json -g globals.json

使用测试数据

newman run collection.json -d data.csv

设置迭代次数

newman run collection.json -n 10

指定报告格式

newman run collection.json -r cli,json,html

输出报告文件

newman run collection.json -r json –reporter-json-export report.json

Newman配置文件

json
// newman.config.json
{
“collection”: “collection.json”,
“environment”: “environment.json”,
“globals”: “globals.json”,
“iterationCount”: 5,
“delay”: 500,
“reporters”: [“cli”, “html”],
“reporter”: {
“html”: {
“export”: “report.html”,
“template”: “custom-template.hbs”
}
}
}

运行:
bash
newman run newman.config.json

六、CI/CD集成

Jenkins集成

1. 安装NodeJS插件

2. Pipeline脚本

groovy
pipeline {
agent any

stages {
stage(‘安装Newman’) {
steps {
sh ‘npm install -g newman’
}
}

stage(‘运行接口测试’) {
steps {
sh ”’
newman run tests/collection.json
-e tests/environment.json
-r cli,html,junit
–reporter-html-export reports/newman-report.html
–reporter-junit-export reports/newman-report.xml
”’
}
}

stage(‘发布报告’) {
steps {
publishHTML([
reportDir: ‘reports’,
reportFiles: ‘newman-report.html’,
reportName: ‘API Test Report’
])
}
}
}

post {
always {
archiveArtifacts artifacts: ‘reports/*’, allowEmptyArchive: true
}
}
}

GitLab CI集成

yaml

.gitlab-ci.yml

stages:
– test

api_test:
stage: test
image: node:18
before_script:
– npm install -g newman
script:
– newman run tests/collection.json
-e tests/environment.json
-r cli,html
–reporter-html-export reports/newman-report.html
artifacts:
paths:
– reports/
expire_in: 1 week

GitHub Actions集成

yaml

.github/workflows/api-test.yml

name: API Test

on:
push:
branches: [main]
pull_request:
branches: [main]

jobs:
test:
runs-on: ubuntu-latest

steps:
– uses: actions/checkout@v3

– name: Setup Node
uses: actions/setup-node@v3
with:
node-version: ’18’

– name: Install Newman
run: npm install -g newman

– name: Run API Tests
run: |
newman run tests/collection.json
-e tests/environment.json
-r cli,html
–reporter-html-export reports/newman-report.html

– name: Upload Report
uses: actions/upload-artifact@v3
with:
name: api-test-report
path: reports/

七、团队协作最佳实践

Collection组织结构


项目Collection/
├── 01-认证模块/
│ ├── 登录
│ ├── 注册
│ └── 刷新Token
├── 02-用户模块/
│ ├── 获取用户列表
│ ├── 获取用户详情
│ ├── 创建用户
│ ├── 更新用户
│ └── 删除用户
├── 03-订单模块/
│ ├── 创建订单
│ ├── 查询订单
│ └── 取消订单
└── 04-公共接口/
├── 文件上传
└── 获取配置

环境管理

创建多个环境:

变量命名规范


// 环境变量:环境相关配置
{{base_url}}
{{api_version}}
{{auth_token}}

// Collection变量:Collection通用配置
{{timeout}}
{{retry_count}}

// Global变量:跨Collection共享
{{test_user}}
{{default_headers}}

Pre-request Script最佳实践

javascript
// 通用请求头设置
pm.request.headers.add({
key: “Content-Type”,
value: “application/json”
});

pm.request.headers.add({
key: “Accept”,
value: “application/json”
});

// 自动添加Token(如果存在)
const token = pm.environment.get(“auth_token”);
if (token) {
pm.request.headers.add({
key: “Authorization”,
value: Bearer ${token}
});
}

// 添加请求ID(用于日志追踪)
pm.request.headers.add({
key: “X-Request-ID”,
value: {{$guid}}
});

Tests Script最佳实践

javascript
// 统一的响应验证模板
pm.test(“API响应验证”, function() {
// 状态码验证
pm.response.to.have.status(200);

// 响应时间验证
pm.expect(pm.response.responseTime).to.be.below(1000);

// 响应结构验证
const json = pm.response.json();
pm.expect(json).to.have.property(“code”);
pm.expect(json).to.have.property(“message”);
pm.expect(json).to.have.property(“data”);

// 业务逻辑验证
if (json.code === 200) {
pm.expect(json.message).to.equal(“success”);
}
});

八、Postman vs RunnerGo

在做接口测试时,除了Postman,RunnerGo也是一个很好的选择:

功能 Postman RunnerGo
接口调试 支持 支持
自动化测试 Newman命令行 可视化编排
Mock Server 支持 支持
性能测试 不支持 内置支持
测试报告 需插件 内置美观报告
团队协作 付费 企业版支持
中文支持 部分中文 完全中文

RunnerGo的优势:

后续第21-25期文章会详细介绍RunnerGo实战。

总结

Postman高级技巧总结:

技术点 用途
变量管理 环境配置、数据传递
Pre-request Script 动态参数、前置处理
Tests Script 断言验证、数据提取
Mock Server 模拟接口、边界测试
Newman CI/CD集成、自动化
Collection Runner 批量测试、数据驱动

掌握这些技巧,Postman不只是接口调试工具,更是强大的自动化测试平台。

参考资料

下期预告:JMeter分布式压测实战 – 从单机到集群的性能测试方案

分享到:

探索 RunnerGo 全栈测试平台

RunnerGo 是一款面向企业的全栈测试平台,集接口测试、自动化测试、性能测试、UI测试于一体,助力企业提升研发效能。

接口测试
性能测试
自动化测试
免费体验 RunnerGo