Python 的Mock测试,代码如下:
test_func.py
class FindFriends(object):
def find_friecds(self):
"""
这是一个开发未完毕的方法:目的是为了寻找朋友
寻找成功返回:{”result“:”success“, “name”: "great boy", "age": 1, "from":"china"}
寻找失败返回:{“result”:”fail“, ”reason“:"your to yang!"}
"""
pass
class FindFriendsStatues(object):
def find_friecds_statues(self):
"""依赖find_friends()接口,进行进一步的页面判断"""
statues = FindFriends().find_friecds()
print(statues)
try:
if statues["result"] == "success":
return "恭喜你,找寻成功!"
elif statues["result"] == "fail":
print("原因是:{}".format(statues["reason"]))
return "查找失败"
else:
return "系统异常错误"
except Exception as e:
return (f"系统错误:{e}")
# if __name__ =="__main__":
# find_friecds_statues()
test_mock_01.py
from unittest import mock
import unittest
from test_func import FindFriends,FindFriendsStatues
class TestFindFriendMethod(unittest.TestCase):
def tearup(self):
pass
@mock.patch("test_func.FindFriends")
def test_01(self, mock_find_friends):
a = mock_find_friends.return_value
a.find_friecds.return_value = {"result": "success","name": "great boy","age": 1,"from": "china"}
statues = FindFriendsStatues().find_friecds_statues()
print(statues)
self.assertEqual(statues, "恭喜你,找寻成功!")
@mock.patch("test_func.FindFriends")
def test_02(self, mock_find_friends):
a = mock_find_friends.return_value
a.find_friecds.return_value = {"result": "fail", "reason": "your to yang!"}
my_result = FindFriendsStatues().find_friecds_statues()
print(my_result)
self.assertEqual(my_result, "查找失败")
def tearDown(self):
pass
if __name__ == "__main__":
unittest.main()
网友评论