postman是一款功能強(qiáng)大的網(wǎng)頁調(diào)試和HTTP請求的Chrome插件。postman里提供完整的斷言方法,無需我們會寫,只要我們能夠使用即可。就像我們不用了解空調(diào)的內(nèi)部結(jié)構(gòu),只要會使用就好。
postman->Tests->右側(cè)單擊所需斷言方法即可添加成功,再進(jìn)行修改使用。

斷言結(jié)果PASS和FAIL

下面具體介紹斷言方法,并結(jié)合具體的接口實(shí)例。
查詢發(fā)布會接口URL:http://127.0.0.1:8000/api/get_event_list/?eid=6&name='ipad發(fā)布會',response body如下:

1、設(shè)置/清除一個(gè)全局變量 (Set/Clear a global variable)
? ? 對應(yīng)腳本:
? ? pm.globals.set("variable_key", "variable_value");
? ? postman.clearGlobalVariable("variable_key");
? ? 參數(shù):需要設(shè)置/清除的變量的key,需要設(shè)置的變量value

2、設(shè)置/清除一個(gè)環(huán)境變量(需要在多個(gè)環(huán)境測試同一個(gè)接口)
? ? Set/Clear an environment variable
? ? 對應(yīng)腳本:
? ? pm.environment.set("variable_key", "variable_value");
? ? pm.environment.unset("variable_key");
? ? 參數(shù):需要清除的環(huán)境變量的key,需要設(shè)置的變量value

3、response包含內(nèi)容(Response body:Contains string)
對應(yīng)腳本如下面兩種:
//發(fā)布會查詢接口response body包含name字段,注意斷言名稱可自行定義,tests["自定義"]
pm.test("Body matches name", function () {? pm.expect(pm.response.text()).to.include("name");});
//簡化方法,發(fā)布會查詢接口response body的limit字段是否包含1000
tests["校驗(yàn)limit是否為1000"] =responseBody.has("1000");

4、將xml格式的response轉(zhuǎn)換成son格式( Response body:Convert XML body to a JSON Object)
對應(yīng)腳本:? var jsonObject = xml2Json(responseBody);

5、response等于預(yù)期內(nèi)容( Response body:Is equal to a string)
對應(yīng)腳本:
? ? tests["Body is correct"] = responseBody === "response_body_string";
? ? 參數(shù):預(yù)期response

6、json解析key的值進(jìn)行校驗(yàn)(Response body:JSON value check)
? ? 對應(yīng)腳本:
? ? tests["Args key contains argument passed as url parameter"] = 'test' in responseJSON.args
? ? 參數(shù):test替換被測的值,args替換被測的key
7、檢查response的header信息是否有被測字段
? ? Response headers:Content-Type header check
? ? 對應(yīng)腳本:tests["Content-Type is present"] = postman.getResponseHeader("Content-Type");
? ? 參數(shù):預(yù)期header

8、響應(yīng)時(shí)間判斷
? ? Response time is less than 200ms
? ? 對應(yīng)腳本: tests["Response time is less than 200ms"] = responseTime < 200;
? ? 參數(shù):響應(yīng)時(shí)間

9、判斷狀態(tài)碼
? ? ? Status code:Code is 200
? ? ? 對應(yīng)腳本:tests["Status code is 200"] = responseCode.code != 400;
? ? ? 參數(shù):狀態(tài)碼

10、檢查code name 是否包含內(nèi)容
? ? ? Status code:Code name has string
? ? ? 對應(yīng)腳本: tests["Status code name has string"] = responseCode.name.has("Created");
? ? ? 參數(shù):預(yù)期code name包含字符串
11、成功的post請求
? ? ? Status code:Successful POST request
? ? ? 對應(yīng)腳本:? tests["Successful POST request"] = responseCode.code === 201 || responseCode.code === 202;
12、微小驗(yàn)證器
? ? ? Use Tiny Validator for JSON data? ? ? ? ? ?
? ? ? 對應(yīng)腳本:
? ? ? ? var schema = {
? ? ? ? "items": {
? ? ? ? "type": "boolean"
? ? ? ? ? ? }
? ? ? ? };
? ? ? ? var data1 = [true, false];
? ? ? ? var data2 = [true, 123];
? ? ? ? console.log(tv4.error);
? ? ? ? tests["Valid Data1"] = tv4.validate(data1, schema);
? ? ? ? tests["Valid Data2"] = tv4.validate(data2, schema);
? ? ? ? 參數(shù):可以修改items里面的鍵值對來對應(yīng)驗(yàn)證json的參數(shù)