在CentOS上实现Postman自动化测试,需先安装Node.js、npm(Newman的依赖)和Newman(Postman命令行工具)。
sudo yum install -y nodejs npm
安装完成后,验证版本:node -v && npm -v
sudo npm install -g newman
验证Newman安装:newman -v
API_Tests),点击“Create”。将需要测试的API请求添加到集合中(如GET/POST请求)。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);
});
"success": true):pm.test("Response contains success field", function () {
const jsonData = pm.response.json();
pm.expect(jsonData.success).to.eql(true);
});
const jsonData = pm.response.json();
pm.environment.set("auth_token", jsonData.token);
collection.json);若使用环境变量,同样导出为environment.json。通过命令行运行Postman集合,实现自动化测试。基础命令如下:
newman run /path/to/collection.json -e /path/to/environment.json
-e:指定环境文件(可选,用于动态替换变量如{{base_url}});--reporters cli,json:生成报告(cli为控制台输出,json为文件报告);--reporter-json-export report.json:将报告保存为JSON文件。newman run /home/user/API_Tests/collection.json -e /home/user/API_Tests/environment.json --reporters cli,json --reporter-json-export /home/user/API_Tests/report.json
执行后,控制台会显示测试结果(通过/失败数量),report.json包含详细结果。将Newman测试集成到CI/CD流程(如Jenkins),实现代码提交后自动运行测试。以Jenkins为例:
sudo yum install -y jenkins
启动Jenkins服务:sudo systemctl start jenkins
# 安装Node.js和Newman(若Jenkins服务器未安装)
sudo yum install -y nodejs npm
sudo npm install -g newman
# 运行Newman测试
newman run /home/user/API_Tests/collection.json -e /home/user/API_Tests/environment.json --reporters cli,json
environment.json)中的变量(如base_url、auth_token)与集合中的变量一致,避免请求失败;sudo或调整文件权限(如chmod +x /path/to/script.sh);--reporters html生成可视化HTML报告,便于团队查看。