Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中实例变量上的模拟方法_Python_Unit Testing_Mocking - Fatal编程技术网

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