1. 程式人生 > >轉載--postman簡單教程,使用tests模組來驗證介面時是否通過

轉載--postman簡單教程,使用tests模組來驗證介面時是否通過

postman簡單教程,使用tests模組來驗證介面時是否通過

轉自--http://www.cnblogs.com/YouxiYouxi/p/7544914.html

介面測試醉重要的就是返回資料的檢查,一個簡單的介面,我們可以肉眼檢查返回資料,但介面一旦多起來且複雜,每次的檢查都會很費勁,此時我們就需要postman 的tests模組來代替

概念:

Postman的test本質上是JavaScript程式碼,通過我們編寫測試程式碼,每一個tests返回True,或是False。

每一個tests實際上就是一個測試用例

 test驗證方式:

內建指令碼說明:

1. 清除一個全域性變數
     Clear a global variable
    對應指令碼:
    postman.clearGlobalVariable("variable_key");
    引數:需要清除的變數的key

2.清除一個環境變數
    Clear an environment variable
    對應指令碼:
    postman.clearEnvironmentVariable("variable_key");
    引數:需要清除的環境變數的key

3.response包含內容
    Response body:Contains string
    對應指令碼:
    tests["Body matches string"] =responseBody.has("string_you_want_to_search");
    引數:預期內容

4.將xml格式的response轉換成son格式
    Response body:Convert XML body to a JSON Object
    對應指令碼:
    var jsonObject = xml2Json(responseBody);
    引數:(預設不需要設定引數,為介面的response)需要轉換的xml

5.response等於預期內容
    Response body:Is equal to a string
    對應指令碼:
    tests["Body is correct"] = responseBody === "response_body_string";
    引數:預期response

6.json解析key的值進行校驗
    Response body:JSON value check
    對應指令碼:
    tests["Args key contains argument passed as url parameter"] = 'test' in responseJSON.args
    引數:test替換被測的值,args替換被測的key

7.檢查response的header資訊是否有被測欄位
    Response headers:Content-Type header check
    對應指令碼:
    tests["Content-Type is present"] = postman.getResponseHeader("Content-Type");
    引數:預期header

8.響應時間判斷
    Response time is less than 200ms
    對應指令碼:
    tests["Response time is less than 200ms"] = responseTime < 200;
    引數:響應時間

9.設定全域性變數
      Set an global variable
      對應指令碼:
      postman.setGlobalVariable("variable_key", "variable_value");
      引數:全域性變數的鍵值

10.設定環境變數
      Set an environment variable
      對應指令碼:
      postman.setEnvironmentVariable("variable_key", "variable_value");
      引數:環境變數的鍵值

11.判斷狀態碼
      Status code:Code is 200
      對應指令碼:
      tests["Status code is 200"] = responseCode.code != 400;
      引數:狀態碼

12.檢查code name 是否包含內容
      Status code:Code name has string
      對應指令碼:
      tests["Status code name has string"] = responseCode.name.has("Created");
      引數:預期code name包含字串

13.成功的post請求
      Status code:Successful POST request
      對應指令碼:
      tests["Successful POST request"] = responseCode.code === 201 || responseCode.code === 202;

14.微小驗證器
       Use Tiny Validator for JSON data            
       對應指令碼: 
        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);
        引數:可以修改items裡面的鍵值對來對應驗證json的引數