1、postman測試接口
(1)首先安裝postman
下載地址:https://www.getpostman.com/apps
選擇對應版本下載,然后安裝即可
(2)使用postman發送請求
比如以下這個請求例子:
使用postman發送請求:
這樣我們可以看到請求返回的內容是否正確。
如果想要把這個做成接口自動化測試,如何處理,請看下一點。
2、接口自動化
(1)安裝python
(2)安裝requests
(3)安裝unittest
(4)安裝pycharm
(5)通過postman獲得初步代碼
我們可以看到初步代碼如下:
import requests url = "https://www.v2ex.com/api/nodes/show.json" querystring = {"name":"python"} payload = "" headers = { 'content-type': "application/json", 'cache-control': "no-cache", 'postman-token': "7590b5ad-8b0a-8336-1a24-b4564a50dba4" } response = requests.request("GET", url, data=payload, headers=headers, params=querystring) print(response.text)
(6)把代碼在pycharm里面重構成我們需要的測試用例代碼:
import requests import unittest class V2exTestCase(unittest.TestCase): def test_node_api(self): url = "https://www.v2ex.com/api/nodes/show.json" querystring = {"name": "python"} response = requests.request("GET", url, params=querystring).json() self.assertEqual("python",response['name']) self.assertEqual(90,response['id']) if __name__=="__main__": unittest.main()
執行結果:
3、總結
- postman可以幫助我們完成50%左右的工作,比如調試接口,導出部分代碼等
- 使用unittest重構用例可以幫助我們添加斷言,提供在命令行執行的能力,很容易跟ci工具進行集成