10-Mock模拟接口返回数据
Posted santiandayu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了10-Mock模拟接口返回数据相关的知识,希望对你有一定的参考价值。
1、安装mock
方法一:pip安装
命令行直接输入:pip install mock
方法二:官网下载mock安装包安装
下载安装包后,解压,命令行进入解压目录,执行python setup.py install
2、mock模拟返回值
1)不封装,mock模拟返回值
# encoding:utf-8 from mock import mock import unittest from base.requestsDemo import SendMain # 创建测试类,继承unittest.TestCase class MockTest(unittest.TestCase): def setUp(self): self.run = SendMain() def test_1(self): # 定义请求的post数据并返回 postData = {‘username‘: ‘wangling‘, ‘password‘: ‘123456‘} # 定义请求的post url postUrl = ‘http://127.0.0.1:8000/postDataHandle/‘ # 定义请求的响应结果 respnse_data = postData # 响应数据 mockData = mock.Mock(return_value=respnse_data) # mockData是send_main方法的模拟值 self.run.send_main = mockData res = self.run.send_main(postUrl, ‘POST‘, postData) print res def test_2(self): getData = {‘username‘: ‘xiaohua‘, ‘mobile‘: ‘13066990001‘, ‘data‘: ‘haha‘} getUrl = ‘http://127.0.0.1:8000/getDataHandle‘ mockData = mock.Mock(return_value=getData) self.run.send_main = mockData res = self.run.send_main(getUrl, ‘GET‘, getData) print res if __name__ == ‘__main__‘: unittest.main()
2)封装,mock模拟返回值
可以将mock模拟返回结果封装一下,使代码重用性更高,具体如下:
# coding:utf-8 from mock import mock # 模拟mock封装 def mock_test(mock_method,url, method,response_data,request_data=None): mock_method = mock.Mock(return_value=response_data) res = mock_method(url, method, request_data) return res
调用如下:
# encoding:utf-8 import unittest from base.requestsDemo import SendMain from base.mockdemoRe import mock_test # 创建测试类,继承unittest.TestCase class MockTest(unittest.TestCase): def setUp(self): self.run = SendMain() def test_2(self): getData = {‘username‘: ‘xiaohua‘, ‘mobile‘: ‘13066990001‘, ‘data‘: ‘haha‘} getUrl = ‘http://127.0.0.1:8000/getDataHandle‘ respnseDate = getData mock_test(self.run.send_main,getUrl,‘GET‘,respnseDate,getData) res = self.run.send_main(getUrl, ‘GET‘, getData) print res if __name__ == ‘__main__‘: unittest.main()
以上是关于10-Mock模拟接口返回数据的主要内容,如果未能解决你的问题,请参考以下文章