Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/297.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_Python 3.5_Python Unittest_Python Asyncio - Fatal编程技术网

Python 模拟已实例化对象的方法

Python 模拟已实例化对象的方法,python,python-3.5,python-unittest,python-asyncio,Python,Python 3.5,Python Unittest,Python Asyncio,我正在编写单元测试,为了进行测试,我想模拟一个已有对象的方法。 但对于asyncio corutines,它看起来并不像看上去那么简单。 我试着使用MagickMock,但它就是不起作用。没有错误或异常,但通过调试器,我可以看到永远不会调用f() 我要修补的测试和对象如下所示: from unittest.mock import patch, MagicMock class Service(object): async def callback_handler(self, msg):

我正在编写单元测试,为了进行测试,我想模拟一个已有对象的方法。 但对于asyncio corutines,它看起来并不像看上去那么简单。 我试着使用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

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

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

我停止使用


尝试使用上下文管理器替换以下行:

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

你的问题有点缺少MCVE。在复制粘贴代码后,我遇到了几个错误:1。在非协同程序函数中使用
wait
test\u my\u case
2。缺少定义
msg()
module.py
。我尽我所能试图纠正这些错误,但如果你能改进你的问题,那就更好了。
with mock.patch.object(self.service, 'callback_handler', side_effect=f) as mock_cb:
    ... # rest of code indented