Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

unit testing - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...