0

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?

doremi
  • 14,921
  • 30
  • 93
  • 148

1 Answers1

0

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())
digitake
  • 846
  • 7
  • 16