打開Postman應用程序,加載需要重試的接口請求集合。右擊目標集合,在彈出菜單中選擇“Run collection”(運行集合)。在彈出的“Collection Runner”窗口中,找到“Iterations”(迭代次數)選項,輸入期望的重試次數(例如10次),點擊“Run”按鈕。Postman將自動重復執行集合中的所有請求,并在結果面板中顯示每次請求的響應詳情(如狀態碼、響應時間、響應體)。
若需要更靈活的重試邏輯(如根據特定狀態碼觸發重試),可通過JavaScript腳本實現:
let attempts = 3; // 最大重試次數
let success = false;
for (let i = 0; i < attempts; i++) {
pm.sendRequest({
url: pm.request.url.toString(), // 當前請求的URL
method: pm.request.method, // 當前請求的方法(GET/POST等)
headers: pm.request.headers, // 當前請求的Headers
body: pm.request.body // 當前請求的Body(若有)
}, (err, response) => {
if (err) {
console.error(`Retry ${i + 1} failed:`, err);
} else if (response.code === 200) {
success = true;
console.log(`Retry ${i + 1} succeeded:`, response.json());
pm.test("Request succeeded after retry", () => pm.expect(response.code).to.eql(200));
} else {
console.log(`Retry ${i + 1} failed with status code: ${response.code}`);
}
if (i === attempts - 1 && !success) {
pm.test("All retries failed", () => pm.expect.fail("Request failed after all retries"));
}
});
}
此腳本會在請求失敗時自動重試,直到達到最大次數或請求成功。若需要將重試策略集成到CI/CD流程中,可使用Postman的命令行工具Newman。通過--iteration-count
參數設置重試次數,例如:
newman run ~/Collections/YourCollection.postman_collection.json \
--environment ~/Environments/YourEnvironment.postman_environment.json \
--iteration-count 5 # 重試5次
該命令會重復運行指定的集合5次,適合自動化測試場景。