python - 模拟已实例化对象的方法

标签 python python-3.5 python-unittest python-asyncio

我编写单元测试并为了测试我想模拟已经存在的对象的方法。 但看起来 asyncio 协程并不像看起来那么简单。 我尝试使用 MagickMock 但它不起作用。没有错误或异常,但通过调试器,我可以看到 f() 从未被调用。

我想要修补的测试和对象如下所示:

from unittest.mock import patch, MagicMock

class Service(object):
   async def callback_handler(self, msg):
      pass

   async def handle(self, msg):
      await self.callback_handler(msg)

class TestCase(object):
    def setUp(self):
      self.service = Service()

    @patch('module.msg')  
    def test_my_case(self, msg_mock):
      f_was_called = False

      async def f():
        global f_was_called   
        f_was_called = True

      self.service.callback_handler = MagicMock(wraps=f) # here I try to mock
      await self.service.handle(msg_mock)
      assert f_was_called is True

如何使用一些自定义方法修补已经实例化的对象方法?协程有什么问题吗?

最佳答案

尝试通过替换此行来使用上下文管理器:

self.service.callback_handler = MagicMock(wraps=f) # here I try to mock

这样:

with mock.patch.object(self.service, 'callback_handler', side_effect=f) as mock_cb:
    ... # rest of code indented

关于python - 模拟已实例化对象的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42388864/

相关文章:

python - 如何在不同版本的 python 上安装 python 模块

python - python 3.6 与旧版本中的字典顺序

python - 使用 python 2.7 从并行目录导入

python - 如何在单元测试中使用 assert_frame_equal

python - 如何获取属性的文档字符串属性?

python - 在 Matplotlib 中设置颜色条的颜色范围

python - 从类实例中获取用户定义的类属性

c++ - 在 python 中嗅探音频?

python - Matplotlib/Seaborn 计算值(Pandas Dataframe)

python - 如何强制 MagicMock 复制函数签名?