Linux环境下Postman Tests脚本使用指南
在Linux系统上使用Postman前,需先完成安装:
.tar.gz格式);tar -xvf Postman-linux-x64-*.tar.gz解压;将解压后的Postman文件夹移动至/opt目录(sudo mv Postman /opt);创建全局符号链接(sudo ln -s /opt/Postman/Postman /usr/local/bin/postman),实现终端直接输入postman启动应用。postman,若成功弹出图形界面则表示安装完成。Content-Type: application/json)和Body(如需发送JSON数据,切换至“Body” tab选择raw→JSON格式输入);Tests脚本主要用于验证响应的正确性,以下是常用场景的示例:
pm.test("Status code is 200", function () {
pm.response.to.have.status(200); // 断言响应状态码为200(成功)
});
pm.test("Response time is less than 200ms", function () {
pm.expect(pm.response.responseTime).to.be.below(200); // 断言响应时间小于200毫秒
});
pm.test("Response body contains expected data", function () {
const jsonData = pm.response.json(); // 解析JSON响应体
pm.expect(jsonData).to.have.property("token"); // 断言响应体包含"token"字段
pm.expect(jsonData.token).to.be.a("string"); // 断言"token"字段为字符串类型
});
// 设置环境变量(如将响应中的token存入环境变量)
pm.test("Set environment variable", function () {
const jsonData = pm.response.json();
pm.environment.set("auth_token", jsonData.token); // 将token存入环境变量"auth_token"
});
// 使用环境变量(如在后续请求的Headers中添加Authorization)
pm.request.headers.add({
key: "Authorization",
value: `Bearer ${pm.environment.get("auth_token")}` // 获取环境变量"auth_token"的值
});
pm.test("Parse XML response", function () {
const xmlData = pm.response.text(); // 获取XML响应体
const jsonObj = xml2Json(xmlData); // 转换为JSON对象(Postman内置xml2Json函数)
pm.expect(jsonObj).to.have.property("root.user.name"); // 断言XML中存在"user.name"节点
});
pm.test("Response header contains Content-Type", function () {
pm.expect(pm.response.headers).to.have.property("Content-Type"); // 断言响应头包含"Content-Type"
pm.expect(pm.response.headers.get("Content-Type")).to.include("application/json"); // 断言"Content-Type"包含"application/json"
});
若需批量执行Collection中的所有请求及脚本,可使用Postman的命令行工具Newman:
npm install -g newman(需提前安装Node.js);newman run /path/to/collection.json -e /path/to/environment.json(collection.json为集合文件路径,environment.json为环境变量文件路径);--reporters cli,html参数生成命令行报告或HTML报告(如newman run collection.json -e environment.json --reporters cli,html)。console.log()函数输出调试信息(如console.log("Response body:", pm.response.json())),可在Postman底部的“Console” tab查看;