使用 postman 給 API 寫測試

使用 postman 給 API 寫測試

Intro

上次咱們簡單介紹了 使用 postman 測試 API,此次主要來寫一些測試用例以檢查請求的響應是否符合咱們的預期以及如何使用腳本測試html

使用 postman 內置的隨機變量

postman 內置的有一些產生隨機值的變量,在發送請求時隨機生成,這樣咱們能夠在請求中隨機生成一些用戶名,郵箱,公司名稱等等,node

支持的變量以下,官方文檔:https://learning.getpostman.com/docs/postman/variables-and-environments/variables-list/git

  • {{$randomZipCode}}
  • {{$randomCity}}
  • {{$randomCityPrefix}}
  • {{$randomCitySuffix}}
  • {{$randomStreetName}}
  • {{$randomStreetAddress}}
  • {{$randomStreetSuffix}}
  • {{$randomStreetPrefix}}
  • {{$randomSecondaryAddress}}
  • {{$randomCountry}}
  • {{$randomCountryCode}}
  • {{$randomState}}
  • {{$randomStateAbbr}}
  • {{$randomLatitude}}
  • {{$randomLongitude}}
  • {{$randomColor}}
  • {{$randomDepartment}}
  • {{$randomProductName}}
  • {{$randomPrice}}
  • {{$randomProductAdjective}}
  • {{$randomProductMaterial}}
  • {{$randomProduct}}
  • {{$randomCompanyName}}
  • {{$randomCompanySuffix}}
  • {{$randomCatchPhrase}}
  • {{$randomBs}}
  • {{$randomCatchPhraseAdjective}}
  • {{$randomCatchPhraseDescriptor}}
  • {{$randomCatchPhraseNoun}}
  • {{$randomBsAdjective}}
  • {{$randomBsBuzz}}
  • {{$randomBsNoun}}
  • {{$randomDatabaseColumn}}
  • {{$randomDatabaseType}}
  • {{$randomDatabaseCollation}}
  • {{$randomDatabaseEngine}}
  • {{$randomDatePast}}
  • {{$randomDateFuture}}
  • {{$randomDateBetween}}
  • {{$randomDateRecent}}
  • {{$randomMonth}}
  • {{$randomWeekday}}
  • {{$randomBankAccount}}
  • {{$randomBankAccountName}}
  • {{$randomCreditCardMask}}
  • {{$randomCurrencyAmount}}
  • {{$randomTransactionType}}
  • {{$randomCurrencyCode}}
  • {{$randomCurrencyName}}
  • {{$randomCurrencySymbol}}
  • {{$randomBitcoin}}
  • {{$randomBankAccountIban}}
  • {{$randomBankAccountBic}}
  • {{$randomAbbreviation}}
  • {{$randomAdjective}}
  • {{$randomNoun}}
  • {{$randomVerb}}
  • {{$randomIngverb}}
  • {{$randomPhrase}}
  • {{$randomImage}}
  • {{$randomAvatarImage}}
  • {{$randomImageUrl}}
  • {{$randomAbstractImage}}
  • {{$randomAnimalsImage}}
  • {{$randomBusinessImage}}
  • {{$randomCatsImage}}
  • {{$randomCityImage}}
  • {{$randomFoodImage}}
  • {{$randomNightlifeImage}}
  • {{$randomFashionImage}}
  • {{$randomPeopleImage}}
  • {{$randomNatureImage}}
  • {{$randomSportsImage}}
  • {{$randomTechnicsImage}}
  • {{$randomTransportImage}}
  • {{$randomImageDataUri}}
  • {{$randomEmail}}
  • {{$randomExampleEmail}}
  • {{$randomUserName}}
  • {{$randomProtocol}}
  • {{$randomUrl}}
  • {{$randomDomainName}}
  • {{$randomDomainSuffix}}
  • {{$randomDomainWord}}
  • {{$randomIP}}
  • {{$randomIPV6}}
  • {{$randomUserAgent}}
  • {{$randomHexColor}}
  • {{$randomMACAddress}}
  • {{$randomPassword}}
  • {{$randomLoremWord}}
  • {{$randomLoremWords}}
  • {{$randomLoremSentence}}
  • {{$randomLoremSlug}}
  • {{$randomLoremSentences}}
  • {{$randomLoremParagraph}}
  • {{$randomLoremParagraphs}}
  • {{$randomLoremText}}
  • {{$randomLoremLines}}
  • {{$randomFirstName}}
  • {{$randomLastName}}
  • {{$randomFullName}}
  • {{$randomJobTitle}}
  • {{$randomNamePrefix}}
  • {{$randomNameSuffix}}
  • {{$randomNameTitle}}
  • {{$randomJobDescriptor}}
  • {{$randomJobArea}}
  • {{$randomJobType}}
  • {{$randomPhoneNumber}}
  • {{$randomPhoneNumberFormat}}
  • {{$randomPhoneFormats}}
  • {{$randomArrayElement}}
  • {{$randomObjectElement}}
  • {{$randomUUID}}
  • {{$randomBoolean}}
  • {{$randomWord}}
  • {{$randomWords}}
  • {{$randomLocale}}
  • {{$randomAlphaNumeric}}
  • {{$randomFileName}}
  • {{$randomCommonFileName}}
  • {{$randomMimeType}}
  • {{$randomCommonFileType}}
  • {{$randomCommonFileExt}}
  • {{$randomFileType}}
  • {{$randomFileExt}}
  • {{$randomDirectoryPath}}
  • {{$randomFilePath}}
  • {{$randomSemver}}

仍是比較偏英文化,對於中文可能並不太友好,下面來演示一個使用示例:github

在請求中使用上面這些變量npm

監控發送的 HTTP 請求json

從上圖中能夠看到,咱們使用到的隨機變量在發送請求的時候是已經替換成具體的值的了api

編寫測試用例

Scripts 介紹

postman 有一套基於 nodejs 的運行時,咱們能夠寫一些 scripts 來在請求發送以前作一些日誌等,在獲得響應以後測試響應是否與預期一致數組

postman 的 script 主要分紅兩類,一類是 Pre-Request Scripts,在發送請求以前執行,一類是 Tests,我的感受可能叫 Post-Response Scripts 更好一些,由於咱們不單單能夠寫測試,也能夠記錄日誌,也能夠設置變量等bash

上次咱們說過了 postman 的測試推薦使用 Collection ,Collection 下能夠分目錄也能夠直接就是 request,目錄裏也能夠有具體的 api request,還能夠有子目錄app

Collection/Folder/Request 均可以定義本身的 Pre-Request ScriptsTests,這些 Scripts 執行順序以下:

上一級的測試做用於子級全部的請求,也就是說咱們能夠在 Collection 的 Test Scripts 中定義一個測試用例,這會對這個 Collection 下的全部請求都有效,都會驗證這個測試是否有效

若是想要實現測試用例的複用能夠將相似的請求放在一個目錄下針對目錄寫測試用例,這樣這個目錄下的請求都會有這個測試用例

若是隻是想針對某一個請求的測試,能夠針對 request 來寫,只在對應 request 的 Test Scripts 中定義便可

Scripts 經常使用語法

Postman Console

postman 是基於 nodejs 的,你能夠直接使用 console.log 來記錄一些日誌,經過 postman console 來查看,在左上角的菜單 View 下有一個 Show Postman Console

咱們在請求的 Pre-Scripts 裏輸出一條日誌,而後發送請求

這裏的 pm.variables.set("phone","") 是設置 phone 這一參數爲空字符串,由下圖能夠看出,phone 這一變量在發送請求的時候會被替換成空字符串

查看 postman console

能夠看到咱們在上面輸出的日誌已經輸出到 postman console 了

變量設置

postman 支持的變量分幾個層級,

  • global
  • environment
  • collection
  • data(數據文件中的變量值)
  • local

變量優化級:

上面的類型優先級從低到高,「就近原則」

// Variables
// This function searches for the variable across globals and the active environment.
var value = pm.variables.get("variable_key"); // 這個方法會從上面全部的來源尋找對應的變量,就近原則,優先從最靠近本身的地方找

// Globals
// Set a global variable,設置一個全局變量
pm.globals.set("variable_key", "variable_value");
// Get a global variable,從全局變量中獲取某個變量的值
pm.globals.get("variable_key");
// Clear a global variable,取消設置全局變量,移除變量
pm.globals.unset("variable_key");

// Environments
// Setting an environment variable, 設置一個環境變量(注,這是postman 中的 <Environment> 環境變量,不一樣於系統環境變量)
pm.environment.set("variable_key", "variable_value");

// 你也能夠序列化一個對象或數組放在變量中
// Setting a nested object as an environment variable
// 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));

// Getting an environment variable,從環境中獲取某個變量
var value = pm.environment.get("variable_key");

// If the value is a stringified JSON:
// 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"));

// // Clear an environment variable, 從環境中移除某一個變量
// pm.environment.unset("variable_key");


// Collection

// Setting an collection variable,設置一個 collection 變量
pm.collectionVariables.set("variable_key", "variableValue");
// Get a collection variable,從 collection 中獲取一個變量 
var val = pm.collectionVariables.get("variable_key");
// Clear a collection variable,從 collection 中移除一個變量
pm.collectionVariables.unset("variable_key");


// local
pm.variables.set("variable_key", "variable_value");

pm.variables.get("variable_key");

使用變量,如 username => {{username}},使用兩層大括號來表示變量引用,好比上面的測試中的 phone

測試用例

postman 的測試用例也是分層級的,上面已經作了簡單的介紹,postman 是基於 nodejs 的因此,在nodejs 裏能夠用的語法大多也都支持,好比 JSON.parse,這裏主要介紹幾種經常使用的方法:

// 檢查 response 的 statusCode 是 200
pm.test("response is ok", function () {
    pm.response.to.have.status(200);
});

// 檢查響應是 200,而且有 body,body 是一個 json
pm.test("response must be valid and has a json 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
});

// 定義一個超時時間,檢查響應時間是否超時
let responseTimeout = parseInt(pm.variables.get("responseTimeout"));
if(responseTimeout > 0){
    pm.test(`Response time is less than ${responseTimeout}ms`, function () {
        pm.expect(pm.response.responseTime).to.be.below(responseTimeout);
    });   
}

// Convert XML body to a JSON object,使用postman 內置的 xml2Json 將 xml 轉換爲 json 對象
var jsonObject = xml2Json(responseBody);

//Check for a JSON value
// 檢查 json 對象中某一個值是否符合預期
pm.test("Your test name", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData.value).to.eql(100);
});

// 檢查數組是否爲空
pm.test("Check if array is empty", function () {
 expect([]).to.be.empty;
});

// 檢查字符串是否爲空
pm.test("Check if string is empty", function () {
 pm.expect('').to.be.empty;
});

運行測試:

測試結果會顯示出多個測試經過,多少失敗的,哪些 assertion 失敗,你也能夠看到具體的響應信息

使用命令行測試

postman 提供了一個 npm 包 newman,咱們能夠直接命令行運行測試,也能夠在本身的程序裏集成 npm 包,在程序裏運行

npm install -g newman

使用導出 Collection, 導出以後是一個 json 文件

newman run testCollection.json // 運行 testCollection 測試

newman run testCollection.json -d testData.json // -d 指定數據文件

newman run testCollection.json -d testData.json -r json // -d 指定數據文件,-r 指定 report 類型,默認是 `cli` 直接在命令行中輸出測試結果

newman run testCollection.json -r cli,json // -d 指定數據文件,-r 指定 report 類型,默認是 `cli` 直接在命令行中輸出測試結果,能夠指定多個 reporter,json 會將運行結果保存到 json 文件中

// collection 路徑不只支持本地路徑,也支持 url
newman run https://www.getpostman.com/collections/631643-f695cab7-6878-eb55-7943-ad88e1ccfd65-JsLv

示例:

在本身的程序中使用 newman 運行測試

const newman = require('newman'); // require newman in your project

// call newman.run to pass `options` object and wait for callback
newman.run({
    collection: require('./sample-collection.json'),
    reporters: 'cli'
}, function (err) {
	if (err) { throw err; }
    console.log('collection run complete!');
});

更多用法參考官方文檔:https://github.com/postmanlabs/newman#using-newman-cli

Reference

原文出處:https://www.cnblogs.com/weihanli/p/write-test-cases-for-api-with-postman.html

相關文章
相關標籤/搜索