简体   繁体   中英

Mocking Methods on an Instance Variable in 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()

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?

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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM