2.1 原理

在接口没有开发完成的时候使用的模拟数据。只要有接口文档,知道数据返回的格式,就可以通过mock去模拟一个请求返回的数据
就和fiddler里面的AutoResponder差不多,拦截到相应请求,然后返回对应响应。
通过模拟返回值来实现,不管传进来的是啥。

  1. # coding=utf-8
  2. import requests
  3. url = "http://www.baidu.com/login"
  4. data = {
  5. "username": "zz",
  6. "password": "1111"
  7. }
  8. def post_request(url, data):
  9. res = requests.post(url, data).json()
  10. return res

2.2 unittest中使用mock

  1. # coding=utf-8
  2. import mock
  3. import requests
  4. import unittest
  5. url = "http://www.baidu.com/login"
  6. data = {
  7. "username": "zz",
  8. "password": "1111"
  9. }
  10. def post_request(url, data):
  11. res = requests.post(url, data).json()
  12. return res
  13. class TestLogin(unittest.TestCase):
  14. def setUp(self):
  15. print("case开始执行")
  16. def tearDown(self):
  17. print("case执行结束")
  18. def test_01(self):
  19. data = {
  20. "username": "11111111"
  21. }
  22. success_test = mock.Mock(return_value=data)
  23. post_request = success_test
  24. res = post_request
  25. self.assertEqual("1112222", res())
  26. if __name__ == "__main__":
  27. unittest.main()

2.3 moco runner

就一个小工具。。。
到moco-runner-0.12.0-standalone.jar这个文件所在文件夹,启动MockRunner服务

  1. java -jar moco-runner-0.12.0-standalone.jar start -p 8801 -c config.json

config.json文件,如果url是/login的时候就返回text是zzy

  1. [{
  2. "request":
  3. {
  4. "url": "/login"
  5. },
  6. "response":
  7. {
  8. "text": "zzy"
  9. }
  10. },
  11. {
  12. "request":
  13. {
  14. #可以设定请求方法
  15. "method": "post"
  16. "url": "/login"
  17. },
  18. "response":
  19. {
  20. #返回字典
  21. "json": {
  22. "user": "111",
  23. "password": "222",
  24. "message": "this is text"
  25. }
  26. }
  27. }]