Python中实例变量上的模拟方法
我试图弄清楚如何正确地模拟一个实例变量,它是另一个类的实例,该类具有父类使用的方法 以下是问题域的简化示例:Python中实例变量上的模拟方法,python,unit-testing,mocking,Python,Unit Testing,Mocking,我试图弄清楚如何正确地模拟一个实例变量,它是另一个类的实例,该类具有父类使用的方法 以下是问题域的简化示例: import unittest import mock class Client: def action(self): return True class Service: def __init__(self): self.client = Client() class Handler: def __init__(self):
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'
如何正确模拟
服务
或客户端
,以便操作
为我的测试用例返回假
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())