1. 准备工作:安装必要工具 在CentOS系统中,首先需要安装Node.js、npm(Node.js包管理器)和Newman(Postman命令行工具)。Node.js是Newman的运行环境,Newman用于在命令行中执行Postman集合测试。安装命令如下:
# 使用yum安装Node.js和npm(CentOS默认仓库版本可能较旧,建议使用NodeSource仓库安装最新版)
curl -fsSL https://rpm.nodesource.com/setup_18.x | sudo bash -
sudo yum install -y nodejs
# 验证安装
node -v # 查看Node.js版本
npm -v # 查看npm版本
# 使用npm全局安装Newman
sudo npm install -g newman
# 验证Newman安装
newman -v # 查看Newman版本
以上步骤确保系统具备运行Postman自动化测试的基础环境。
2. 创建Postman测试集合与脚本 Postman测试的核心是集合(Collection),用于组织多个API请求。创建集合的步骤如下:
Content-Type: application/json)。pm.test("Status code is 200", function () { pm.response.to.have.status(200); });pm.test("Response time is less than 200ms", function () { pm.expect(pm.response.responseTime).to.be.below(200); });pm.test("Response contains expected data", function () { const jsonData = pm.response.json(); pm.expect(jsonData.key).to.eql("expectedValue"); });my-api-tests.json)。3. 使用Newman运行自动化测试 导出集合后,可通过Newman在命令行中执行测试。基本命令格式为:
newman run <collection-file-path> [options]
常用选项说明:
-e <environment-file>:指定环境变量文件(如environment.json,用于管理URL、Token等变量,避免硬编码);--reporters cli,json:生成命令行报告和JSON格式报告(便于后续分析);--reporter-json-export <report-path>:指定JSON报告保存路径。newman run /path/to/my-api-tests.json -e /path/to/environment.json --reporters cli,json --reporter-json-export /path/to/report.json
执行后,命令行会显示测试结果的实时状态(通过/失败),并生成报告文件。
4. 自动化脚本封装(可选)
为简化测试流程,可编写Shell脚本封装Newman命令。例如创建run_postman.sh:
#!/bin/bash
# 设置集合和环境文件路径
COLLECTION_FILE="/path/to/my-api-tests.json"
ENVIRONMENT_FILE="/path/to/environment.json"
# 运行Newman并生成报告
newman run "$COLLECTION_FILE" -e "$ENVIRONMENT_FILE" --reporters cli,json --reporter-json-export "/path/to/report.json"
# 检查测试结果(根据报告中的failures字段判断)
if grep -q '"failures": 0' /path/to/report.json; then
echo "All tests passed!"
exit 0
else
echo "Some tests failed!"
exit 1
fi
赋予脚本执行权限并运行:
chmod +x run_postman.sh
./run_postman.sh
脚本会根据测试结果返回退出码(0表示全部通过,1表示有失败),便于后续集成到CI/CD流程。
5. 集成到CI/CD流程(可选) 将Postman自动化测试集成到CI/CD(如Jenkins)中,可实现代码提交或部署时自动运行测试。以Jenkins为例,步骤如下:
./run_postman.sh);newman-reporter-junit插件);pipeline {
agent any
stages {
stage('Run Postman Tests') {
steps {
sh './run_postman.sh'
}
}
}
post {
always {
junit '/path/to/report.xml' // 需将Newman的JSON报告转换为XML格式
}
}
}
集成后,团队可实时监控API测试状态,及时发现代码变更导致的问题。