前面兩個章節 [Postman 實用接口測試系列 1 - 基礎] 和 [Postman 實用接口測試系列 2 - 接口依賴] 咱們介紹了postman的具體使用和如何處理接口依賴。今天要介紹的是若是寫測試用例。 這一部分就和咱們測試童鞋更息息相關了。json
大綱: * 測試用例編寫的3A原則 * 腳本類型 * 如何編寫腳本
接口測試簡單的說就是建立一個請求,發送請求,而後判斷請求的結果是不是指望的。數組
對於測試用例的編寫能夠參考3A原則:異步
對應的postman的模塊以下圖:post
咱們接下來的就會分別講解這個幾個模塊的內容。測試
pre-request和test腳本有三種類型:spa
對於pre-request和test腳本執行順序都是: collection > folder > request, 以下圖debug
固然若是你只有一個請求,pre-request 和 test腳本都在這個請求上,那它的順序就簡單多了。3d
不一樣層級的腳本,能夠實現腳本的複用,好比同一個collection下的腳本,咱們都有一個共同的test是判斷返回結果是200,那這個test就能夠寫在collection的腳本里。而後request只須要寫本身特殊的test。
首先使用的語言是Javascript,咱們在腳本中可使用的幾個主要模塊有。code
pm.response
: 能夠得到返回的結果pm.test
定義測試用例,用例名字,方法,方法返回一個 true/false 的布爾值,來判斷用例pass仍是fail。pm.expect
來作斷言//數組 pm.expect([1, 2, 3]).to.include(2); //json pm.expect({a: 1, b: 2, c: 3}).to.include({a: 1, b: 2}); //先判斷類型更好 pm.expect([1, 2, 3]).to.be.an('array').that.includes(2); //判斷返回的response body 是否含有某個字符串 pm.expect(pm.response.text()).to.include("string_you_want_to_search"); //判斷是否含有子串 pm.expect('foobar').to.have.string('bar'); //判斷是否包含某個jsonBody pm.response.to.have.jsonBody(""); //判斷是否不包含某個jsonBody pm.response.to.not.have.jsonBody("error");
//判斷環境 pm.expect(pm.environment.get("env")).to.equal("production"); //判斷返回的response body 是否等於某個字符串 pm.response.to.have.body("response_body_string"); //判斷返回的json內容 var jsonData = pm.response.json(); pm.expect(jsonData.value).to.eql(100); //判斷兩個數組裏元素是否相同 pm.expect([1, 2, 3]).to.have.members([2, 1, 3]); //判斷返回狀態碼是不是201,202中一個 pm.expect(pm.response.code).to.be.oneOf([201,202]);
expect([]).to.be.empty pm.expect('').to.be.empty; //先判斷類型,而後判斷是否爲空 pm.expect([]).to.be.an('array').that.is.empty;
//判斷類型是不是string,object或者undefined pm.expect('Postman').to.be.a('string'); pm.expect({a: 1}).to.be.an('object'); pm.expect(undefined).to.be.an('undefined');
//判斷響應時長是否低於200ms pm.expect(pm.response.responseTime).to.be.below(200); //判斷長度 pm.expect('foo').to.have.lengthOf(3); //判斷個數 pm.expect([1, 2, 3]).to.have.lengthOf(2); //判斷response pm.response.to.not.be.error; pm.response.to.be.ok; pm.response.to.be.withBody; pm.response.to.be.json; //判斷Content-Type是否出現 pm.response.to.have.header("Content-Type"); //判斷返回狀態碼是不是200 pm.response.to.have.status(200); //返回狀態碼是否含有某個字符串 pm.response.to.have.status("Created") //把xml body轉成JSON var jsonObject = xml2Json(responseBody); //發送異步請求 pm.sendRequest("https://postman-echo.com/get", function (err, response) { console.log(response.json()); });
//是否含有集合裏的全部的key pm.expect({a: 1, b: 2}).to.have.all.keys('a', 'b'); //是否含有一個集合中的某個key pm.expect({a: 1, b: 2}).to.have.any.keys('a', 'b'); //是否不含集合中的任何key pm.expect({a: 1, b: 2}).to.not.have.any.keys('c', 'd'); //先判斷類型,再判斷keys pm.expect({a: 1, b: 2}).to.be.an('object').that.has.all.keys('a', 'b');
小技巧,通常在作斷言以前先使用.a先來判斷類型效果更好
咱們這裏寫一個簡單的單個請求的Test。判斷返回狀態碼是不是200,某個參數的值是不是對的xml