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查看;