from unittest import mock
result = mock.Mock(name='mock的名称')
print(result)
# 结果:
<Mock name='mock的名称' id='2721150378120'>
return_value
side_effect
import unittest
from unittest import mock
class Test01(unittest.TestCase):
def weather(self):
'''天气接口'''
# result = {'result': "雪", 'status': '下雪了!'}
pass
def weather_result(self):
'''模拟天气接口返回值'''
result = Test01.weather(self)
if result['result'] == '雪':
print('下雪了!!!')
elif result['result'] == '雨':
print('下雨了!!!')
elif result['result'] == '晴天':
print('晴天!!!!')
else:
print('返回值错误!')
return result['status']
def test_01(self):
'''模拟下雪天场景'''
mock_xue_result = {'result': "雪", 'status': '下雪了!'}
# 使用mock库进行模拟
Test01.weather = mock.Mock(return_value=mock_xue_result)
statues = Test01.weather_result(self)
self.assertEqual(statues, '下雪了!')
def test_02(self):
'''模拟下雨天场景'''
mock_yu_result = {'result': "雨", 'status': '下雨了!'}
# 使用mock库进行模拟
Test01.weather = mock.Mock(return_value=mock_yu_result)
statues = Test01.weather_result(self)
self.assertEqual(statues, '下雨了!')
if __name__ == '__main__':
unittest.main()
# w1.py
def weather():
'''天气接口'''
pass
def weather_result():
'''模拟天气接口返回值'''
result = weather()
if result['result'] == '雪':
print('下雪了!!!')
elif result['result'] == '雨':
print('下雨了!!!')
elif result['result'] == '晴天':
print('晴天!!!!')
else:
print('返回值错误!')
return result['status']
import unittest
from unittest import mock
# 导入接口文件
import w1
class Test01(unittest.TestCase):
@mock.patch(target="w1.weather")
def test_01(self, mock_login):
'''下雪了'''
mock_login.return_value={'result': "雪", 'status': '下雪了!'}
statues = w1.weather_result()
self.assertEqual(statues, '下雪了!')
@mock.patch(target='w1.weather')
def test_02(self,mock_login):
'''下雨了!'''
mock_login.return_value = {'result': "雨", 'status': '下雨了!'}
statues = w1.weather_result()
self.assertEqual(statues, '下雨了!')
if __name__ == '__main__':
unittest.main()
如果感觉安静写的对您有帮助可以点个关注,持续更新中~~也可以关注安静的个人公众号进行来一起学习探讨测试内容
-------------------------------------------------------------------------------------------------------------------------------------------------------------