在 Ubuntu 上使用 Postman 进行数据驱动测试
一 准备数据与集合
username,password
user1,pass1
user2,pass2
[
{ "username": "user1", "password": "pass1" },
{ "username": "user2", "password": "pass2" }
]
二 在 Postman 图形界面运行数据驱动测试
三 在 Ubuntu 终端使用 Newman 批量运行
npm install -g newman
# 基本运行
newman run my-api-tests.json -d data.csv
# 使用环境变量文件
newman run my-api-tests.json -d data.json -e dev.env.json
# 生成 HTML 报告(需 newman-reporter-html)
npm install -g newman-reporter-html
newman run my-api-tests.json -d data.csv -r html --reporter-html-export report.html
四 关键脚本示例
pm.test("Status code is 200", () => {
pm.response.to.have.status(200);
});
pm.test("Response contains expected username", () => {
const json = pm.response.json();
pm.expect(json.username).to.eql(data.username);
});
pm.collectionVariables.set("username", pm.iterationData.get("username"));
pm.collectionVariables.set("password", pm.iterationData.get("password"));
pm.request.headers.add({
key: "Authorization",
value: "Bearer " + pm.environment.get("token")
});
console.log("Current username:", pm.iterationData.get("username"));
以上脚本使用 pm 对象完成前置处理、断言与日志输出,适配数据驱动迭代执行。
五 常见问题与最佳实践