Postman - 斷言



斷言用於驗證測試執行後實際值和預期值是否匹配。如果它們不匹配,則測試將失敗,我們將從測試輸出中獲得失敗原因。

斷言返回布林值 true 或 false。在 Postman 中,我們可以藉助 JavaScript Chai 斷言庫在我們的測試中新增斷言。它在 Postman 應用程式中自動可用。

Chai 斷言易於理解,因為它們以人類可讀的格式定義。Postman 中的斷言寫在位址列下的“測試”選項卡中。

Chai 的文件可在以下連結中找到:

https://www.chaijs.com/

Assertion

編寫斷言

讓我們編寫一個斷言來檢查特定文字 - Postman 是否在一個字串陣列中

示例

pm.test["Text is present"], function(){
	pm.expect(['Java', 'Postman']).to.include('Postman')
})

輸出

輸出如下:

Assertion1

讓我們編寫一個斷言來檢查陣列是否為空

示例

pm.test["Array contains element"], function(){
	pm.expect(['Java', 'Postman']).to.be.an('array').that.is.not .empty
})

輸出

輸出如下:

Assertion2

物件驗證斷言

讓我們用 eql 編寫一個物件驗證斷言。它用於比較下面示例中物件 i 和 j 的屬性。

示例

pm.test("Equality", function(){
let i = {
	"subject" : "Postman"
};
let j= {
	"subject" : "Cypress"
};
pm.expect(i).to.not.eql(j);

輸出

輸出如下:

Assertion3

物件 i 定義的屬性是 Postman,而物件 j 定義的屬性是 Cypress。因此,not.eql 斷言通過了。

斷言型別

在 Postman 中,我們可以對響應的不同部分應用斷言。這些將在下面解釋:

狀態碼

The assertion for status code is as follows:pm.test["Status Code is 401"], function(){
	pm.response.to.have.status(401)
})

如果獲得的響應狀態碼為 401,則上述斷言透過。

pm.test["Status is Forbidden"], function(){
	pm.response.to.have.property('status', ' Forbidden')
})

上述斷言應用於具有值“Forbidden”的響應屬性 - status。

響應花費的時間

響應花費時間的斷言如下:

pm.test("Response time above 500 milliseconds", function () {
	pm.expect(pm.response.responseTime).to.be.above(500)
})

如果響應時間超過 500 毫秒,則上述斷言透過。

響應格式的型別

響應格式型別的斷言如下:

pm.test("Response type is JSON", function(){
	pm.response.to.be.json;
})

如果響應為 JSON 型別,則上述斷言透過。

響應的頭

響應頭的斷言如下:

pm.test("Header Content-Encoding is available", function () {
	pm.response.to.have.header("Content-Encoding")
})

如果響應具有 Content-Encoding 頭,則上述斷言透過。

響應的文字

響應文字的斷言如下:

pm.test("Response Text", function () {
	pm.expect(pm.response.text()).to.include("Tutorialspoint")
})

如果響應文字包含文字 Tutorialspoint,則上述斷言透過。

廣告