【问题标题】:Mock a method of already instantiated object模拟已实例化对象的方法
【发布时间】:2017-02-22 10:40:07
【问题描述】:

我编写单元测试并且为了测试我想模拟一个已经存在的对象的方法。 但看起来使用 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

如何用一些自定义方法修补已经实例化的对象方法?协程是否存在一些问题?

【问题讨论】:

  • 您的问题有点缺乏提供 MCVE。在复制粘贴您的代码后,我遇到了几个错误:1. 在非协程函数test_my_case 中使用await 2. 缺少定义msg()module.py。我试图尽我所能修复这些错误,但如果你改进你的问题会更好。

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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    我在尝试模拟 asyncio 时也遇到了问题,并希望遇到很多麻烦,

    我结束了使用pytest.asycio plugin

    @pytest.mark.asyncio
    async def test_some_asyncio_code():
        res = await library.do_something()
        assert b'expected result' == res
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多