在Linux下使用Postman进行脚本自动化测试,可按以下步骤操作:
安装依赖工具
sudo apt-get update && sudo apt-get install nodejs npm
npm install -g newman
创建测试集合
my-api-tests.json)。
// 检查状态码
pm.test("Status code is 200", function() {
pm.response.to.have.status(200);
});
// 检查响应体包含特定字段
pm.test("Response has 'id' field", function() {
const jsonData = pm.response.json();
pm.expect(jsonData).to.have.property("id");
});
编写运行脚本
run-tests.js文件,调用Newman运行集合:const newman = require('newman');
newman.run({
collection: 'path/to/my-api-tests.json',
// 可选:指定环境变量文件
// environment: 'path/to/env.json',
reporters: 'cli', // 输出格式(cli/html/json/junit)
}, function(err, summary) {
if (err) console.error(err);
console.log(summary);
});
执行测试
node run-tests.js
集成到CI/CD(可选)
说明:
pm对象操作请求和响应。pm.environment、pm.iterationData实现。