Python中实例变量的模拟方法 [英] Mocking Methods on an Instance Variable in Python
本文介绍了Python中实例变量的模拟方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试找出如何正确模拟一个实例变量,该实例变量是具有父类使用的方法的另一个类的实例.
I'm trying to figure out how to properly Mock an instance variable which is an instance of another class that has methods used by the parent class.
这是问题域的简化示例:
Here's a simplified example of the problem domain:
import unittest
import mock
class Client:
def action(self):
return True
class Service:
def __init__(self):
self.client = Client()
class Handler:
def __init__(self):
self._service = Service()
def example(self):
return self._service.client.action()
class TestHandler(unittest.TestCase):
@mock.patch('__main__.Handler._service')
def test_example_client_action_false(self):
"""Test Example When Action is False"""
handler = Handler()
self.assertFalse(handler.example())
if __name__ == '__main__':
unittest.main()
结果测试引发:
AttributeError: __main__.Handler does not have the attribute '_service'
如何正确模拟Service
或Client
,以使action
为测试用例返回False
?
How do I properly mock the Service
or Client
such that action
returns False
for my test case?
推荐答案
可以通过模拟操作返回值来完成
Can be done by mock the action return value
class TestHandler(unittest.TestCase):
@mock.patch('__main__.Client.action')
def test_example_client_action_false(self, mock_client_action):
"""Test Example When Action is False"""
mock_client_action.return_value = False
handler = Handler()
self.assertFalse(handler.example())
这篇关于Python中实例变量的模拟方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文