在Linux系统上运行Postman自动化测试前,需安装以下工具:
sudo apt-get update
sudo apt-get install nodejs npm
linux64),解压后将其可执行文件链接到系统PATH:wget https://dl.pstmn.io/download/latest/linux64 -O postman.tar.gz
tar -xzf postman.tar.gz -C /opt
sudo ln -s /opt/Postman/Postman /usr/local/bin/postman
npm install -g newman
以上步骤完成后,可通过postman --version和newman --version验证安装是否成功。
在Postman桌面客户端中完成测试用例的设计与集合导出:
My API Tests),点击“Create”。https://api.example.com/endpoint),配置请求头(Headers)、参数(Params)或Body(如JSON格式)。pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
pm.test("Response contains token", function () {
const jsonData = pm.response.json();
pm.expect(jsonData).to.have.property("token");
});
pm.test("Response time is fast", function () {
pm.expect(pm.response.responseTime).to.be.below(500);
});
my-api-tests.json文件。若测试需切换不同环境(如开发、测试、生产),可创建环境文件管理变量:
Dev Environment),添加变量(如base_url: https://api-dev.example.com),点击“Add”。{{variable_name}}语法(如{{base_url}}/endpoint)。environment.json文件。通过Node.js脚本调用Newman运行Postman集合,实现命令行自动化:
run-tests.js),内容如下:const newman = require('newman');
newman.run({
collection: './my-api-tests.json', // 集合文件路径
environment: './environment.json', // 环境文件路径(可选)
reporters: 'cli', // 输出到命令行
reporter: { // 可选:生成HTML报告
html: {
export: './reports/report.html' // 报告保存路径
}
}
}, function (err, summary) {
if (err) {
console.error('测试运行失败:', err);
return;
}
console.log('测试完成:', summary.run.stats);
});
node run-tests.js命令运行,即可在终端查看测试结果(如通过/失败的用例数、响应时间等)。为便于分析测试结果,可生成可视化报告:
npm install -g newman-reporter-html
run-tests.js中的reporters配置,添加html reporter(如上文脚本所示),运行后会在./reports/目录生成report.html文件,用浏览器打开即可查看详细报告。将自动化测试集成到CI/CD流程(如Jenkins、GitLab CI),实现代码提交后自动运行测试:
Jenkinsfile中添加以下步骤:pipeline {
agent any
stages {
stage('Run Postman Tests') {
steps {
sh 'npm install -g newman' // 安装Newman
sh 'newman run ./my-api-tests.json -e ./environment.json --reporters cli' // 运行测试
}
}
}
}
.gitlab-ci.yml文件,添加以下内容:stages:
- test
postman_tests:
stage: test
image: node:latest // 使用Node.js镜像
script:
- npm install -g newman
- newman run ./my-api-tests.json -e ./environment.json
集成后,每次代码提交或推送时,CI/CD工具会自动触发测试脚本,确保API变更未引入缺陷。通过以上步骤,即可在Linux系统上实现Postman自动化测试,覆盖从测试设计、执行到结果分析的全流程,并与CI/CD系统集成,提升API测试效率与可靠性。