用Postman作接口測試

The higher your test coverage, the more flexible and bug-resistant your code will be, and the less time you’ll spend debugging hot fixes in production.javascript

測試覆蓋率越高,代碼就越靈活,生產中調試修補程序所花費的時間就越少。java

首先,很遺憾的一點是,Postman不支持併發測試,但支持指定次數與間隔時間的串行測試。npm

官方文檔連接:Postman Test scriptsjson

postman請求流程

Postman請求流程圖

postman test 配置

測試容許配置在Collections/Folder/Request中,配置在Collections/Folder中方便咱們統一的對多接口進行測試。api

Postman Test 是在接受到請求響應Response後執行的一段JavaScript代碼。在發送請求並從服務器收到響應後Postman將運行測試腳本。。在Postman Request Builder中,請求部分包含一個Tests標籤,返回部分包含一個Test Result標籤。
在Tests標籤右邊,羅列了一些輔助編寫的經常使用代碼段。服務器

使用PM API:pm.* API 編寫測試代碼

pm.test()

  • 使用pm.test()函數可以在Postman test Sandbox中編寫測試規範。使用此函數容許你準確命名某個測試,而且確保測試腳本中的某個錯誤並不會阻塞其他部分的執行。
  • pm.test()接受兩個參數:(string testName, A Function witch resturn boolean value).
// example using pm.response.to.have
pm.test("response is ok", function () {
   pm.response.to.have.status(200);
});

// example using pm.expect()
pm.test("environment to be production", function () {
   pm.expect(pm.environment.get("env")).to.equal("production");
});

// example using response assertions
pm.test("response should be okay to process", function () {
   pm.response.to.not.be.error;
   pm.response.to.have.jsonBody("");
   pm.response.to.not.have.jsonBody("error");
});

// example using pm.response.to.be*
pm.test("response must be valid and have a body", function () {
    // assert that the status code is 200
    pm.response.to.be.ok; // info, success, redirection, clientError,  serverError, are other variants
    // assert that the response has a valid JSON body
    pm.response.to.be.withBody;
    pm.response.to.be.json; // this assertion also checks if a body  exists, so the above check is not needed
});

### pm.* 輔助函數網絡

  • pm.expect() 斷言函數創建在流行的JavaScript測試庫ChaiJS BDD的基礎上,編寫可讀測試。
  • pm.response.to.be.* 函數簡化斷言。使用此係列斷言可簡化對響應狀態類型和主體變體的測試。

After Test

  • 執行請求後,在TestResutl標籤下,能夠查看測試是否經過。
  • 使用Collection Runner能夠實時查看請求是否經過測試。

自動化測試

須要命令行工具與持續集成工具或持續交付工具(如Jenkins或Travis CI)集成來自動化您的測試。併發

測試代碼樣例

//設置環境變量
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");

//獲取環境變量(其值是字符串化對象)
// These statements should be wrapped in a try-catch block if the data is coming from an unknown source.
var array = JSON.parse(pm.environment.get("array"));
var obj = JSON.parse(pm.environment.get("obj"));

//清除環境變量
pm.environment.unset("variable_key");

//設置全局變量
pm.globals.set("variable_key", "variable_value");

//獲取全局變量
pm.globals.get("variable_key");

//清除全局變量
pm.globals.unset("variable_key");

//獲取變量:此函數在全局變量和活動環境中搜索變量
pm.variables.get("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);
});

//Content-Type是否存在
pm.test("Content-Type is present", function () {
    pm.response.to.have.header("Content-Type");
});

//響應時間小於200毫秒
pm.test("Status code is 200", function () {
    pm.response.to.have.status(200);
});

//Code name contains a string: 檢查Code name包含指定string。網絡基礎知識很差,不太理解這一句話Orz
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]);
});

//使用TinyValidator獲取JSON數據
var schema = {
 "items": {
 "type": "boolean"
 }
};
var data1 = [true, false];
var data2 = [true, 123];
pm.test('Schema is valid', function() {
  pm.expect(tv4.validate(data1, schema)).to.be.true;
  pm.expect(tv4.validate(data2, schema)).to.be.true;
});

//解碼base64編碼數據
var intermediate,
    base64Content, // assume this has a base64 encoded value
    rawContent = base64Content.slice('data:application/octet-stream;base64,'.length);

intermediate = CryptoJS.enc.Base64.parse(base64content); // CryptoJS is an inbuilt object, documented here: https://www.npmjs.com/package/crypto-js
pm.test('Contents are valid', function() {
  pm.expect(CryptoJS.enc.Utf8.stringify(intermediate)).to.be.true; // a check for non-emptiness
});

//發送異步請求
pm.sendRequest("https://postman-echo.com/get", function (err, response) {
    console.log(response.json());
});

//將XML主體轉換爲JSON對象
var jsonObject = xml2Json(responseBody);
相關文章
相關標籤/搜索