前言
當一個接口發送請求有返回結果后,如何知道返回的結果符合預期?可以在 postman 里面的 Tests 寫腳本斷言符合結果符合預期。
Tests 是接口返回 response 之后的腳本操作,可以使用 JavaScript 為 Postman API 請求編寫 Tests 腳本。
Tests編寫
Tests 可以添加到單個請求,文件夾和集合中,這里以單個請求為例。
登陸接口返回
{
"code": 0,
"msg": "login success!",
"username": "test",
"token": "580406b0df935496f96313fc98ae7e18d39d62af"
}
校驗返回的 body 是 json 格式
首先可以校驗返回的body是json格式
pm.test("response must be valid and have a body", function () {
pm.response.to.be.ok;
pm.response.to.be.withBody;
pm.response.to.be.json;
});
運行后可以看到接口返回TestResults位置顯示PASS,說明此校驗通過
校驗body具體內容
上面是直接pm.response.to.be
方式對response對象校驗的,也可以用pm.expect(actual_result).to
方式對提取的返回結果校驗
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/
// 校驗code為0
pm.test("response code must to be 0", function () {
pm.expect(pm.response.json().code).to.equal(0);
});
//校驗msg 為 login success!
pm.test("response msg must to be login success!", function () {
pm.expect(pm.response.json().msg).to.equal("login success!");
});
//校驗token 長度為40位
pm.test("response token length must to be 40", function () {
pm.expect(pm.response.json().token).to.lengthOf(40);
});
校驗狀態碼和返回頭部
校驗返回狀態碼是200
pm.test("Status test", function () {
pm.response.to.have.status(200);
});
校驗返回頭部參數
校驗 Content-Type 在返回頭部
pm.test("Content-Type header is present", () => {
pm.response.to.have.header("Content-Type");
});
校驗返回的頭部Content-Type 值為 application/json
pm.test("Content-Type header is application/json", () => {
pm.expect(pm.response.headers.get('Content-Type')).to.eql('application/json');
});
斷言返回值與變量相等
如果我前面登陸的body參數引用了環境變量username
接口返回的json數據又有這個賬號名稱,想斷言結果返回的值和變量username相等,於是可以先獲取環境變量值
pm.environment.get("name");
於是腳本這樣寫
pm.test("Response property matches environment variable", function () {
pm.expect(pm.response.json().username).to.eql(pm.environment.get("username"));
});
作者-上海悠悠 blog地址 https://www.cnblogs.com/yoyoketang/