【问题标题】:Mocking Methods on an Instance Variable in Python在 Python 中模拟实例变量的方法
【发布时间】:2017-06-08 17:50:55
【问题描述】:

我正在尝试弄清楚如何正确模拟一个实例变量,该实例变量是另一个类的实例,该类具有父类使用的方法。

这是问题域的简化示例:

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'

如何正确模拟 ServiceClient 以使 action 为我的测试用例返回 False

【问题讨论】:

    标签: python unit-testing mocking


    【解决方案1】:

    可以通过mock动作返回值来完成

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

    【讨论】:

      猜你喜欢
      • 2013-07-17
      • 1970-01-01
      • 2020-06-17
      • 1970-01-01
      • 1970-01-01
      • 2011-06-29
      • 1970-01-01
      • 2012-08-23
      相关资源
      最近更新 更多