前戲
在我們測接口的時候,沒有斷言的接口都是耍流氓,因為做自動化的時候,不加斷言我們不知道這個接口是執行成功了還是執行失敗了,所以斷言是做接口自動化必須的
斷言
斷言就是我們預期值和接口返回值是否一樣,就和我們寫功能測試用例時的預期結果一個意思
pre-request Script(預置腳本)可以用來修改一些默認參數,在請求發送之前執行
test Scripr(測試腳本):當接受到響應之后,在執行腳本
還是我們上節講的A接口,我們來斷言返回值中是不是有zouzou666,如果有,則認為接口執行成功,沒有則失敗
在test里設置斷言
pm.test("包含字符串",function(){
pm.expect(pm.response.text()).to.include("zouzou666");
});
如果執行成功則在Test Results里顯示PASS,那我們把斷言改為失敗試試
我們發現,斷言失敗會顯示成FALL的,當然我們可以在Test下面添加多個斷言
postman腳本執行順序
也就是先執行最上層的文件夾里的pre-request Script,在執行它下面文件夾里的pre-request Script,在執行請求里的pre-request Script。在發送請求,在執行最上層的文件夾里的Tests,在執行它下面文件夾里的Tests,最后執行請求里的Tests
常用的斷言
判斷返回結果是不是在1s之內
pm.test("返回結果在1s之內",function(){
pm.expect(pm.response.responseTime).to.be.below(1000);
});
判斷返回結果是不是在300ms左右
pm.test("判斷返回結果在300ms左右",function(){
pm.expect(pm.response.responseTime).to.be.closeTo(300,200);
});在300ms的上下200ms,也就是100--500ms之間
斷言返回的狀態碼是不是200
tests["返回狀態碼正確"]=responseCode.code===200; pm.test("返回正確",function(){ // pm.response.to.have.status(200); pm.response.to.be.ok; })
pm.test("包含字符串",function(){ pm.expect(pm.response.text()).to.include("@#sd1135"); }); pm.test("包含字符串",function(){ pm.expect(pm.response.text()).to.include("38dd572dd9c14c73b7637893c0592aa7"); }); pm.test("包含字符串",function(){ pm.expect(pm.response.text()).to.include("10"); });
設置環境變量
pm.environment.set("variable_key", "variable_value");
將嵌套對象設置為環境變量
var array = [1, 2, 3, 4]; pm.environment.set("array", JSON.stringify(array, null, 2)); var obj = { a: [1, 2, 3, 4], b: { c: 'val' } }; pm.environment.set("obj", JSON.stringify(obj));
獲取環境變量
pm.environment.get("variable_key");
獲取環境變量(其值是字符串化對象)
var array = JSON.parse(pm.environment.get("array")); var obj = JSON.parse(pm.environment.get("obj"));
清除環境變量
pm.environment.unset("variable_key");
設置全局變量
pm.globals.get("variable_key");
清除全局變量
pm.globals.unset("variable_key");
檢查響應主體是否包含字符串
pm.test("Body matches string", function () { pm.expect(pm.response.text()).to.include("string_you_want_to_search"); });
檢查響應主體是否等於字符串
pm.test("Body is correct", function () { pm.response.to.have.body("response_body_string"); });
檢查JSON值
pm.test("Your test name", function () { var jsonData = pm.response.json(); pm.expect(jsonData.value).to.eql(100); });
內容類型存在
pm.test("Content-Type is present", function () { pm.response.to.have.header("Content-Type"); });
響應時間小於200毫秒
pm.test("Response time is less than 200ms", function () { pm.expect(pm.response.responseTime).to.be.below(200); });
狀態代碼是200
pm.test("Status code is 200", function () { pm.response.to.have.status(200); });
代碼名稱包含一個字符串
pm.test("Status code name has string", function () { pm.response.to.have.status("Created"); });
成功的POST請求狀態代碼
pm.test("Successful POST request", function () { pm.expect(pm.response.code).to.be.oneOf([201,202]); });