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()
The resulting test raises:
AttributeError: __main__.Handler does not have the attribute '_service'
How do I properly mock the Service
or Client
such that action
returns False
for my test case?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…