在obj上仅模拟一个方法

2024-05-29 04:26:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我熟悉其他语言中的mocking库,比如Java中的Mockito,但是Python的mock库让我的生活变得混乱。

我有下面一节课要考。

class MyClassUnderTest(object):

    def submethod(self, *args):
       do_dangerous_things()

    def main_method(self):
       self.submethod("Nothing.")

在我的测试中,我希望确保在执行main_method时调用submethod,并且使用正确的参数调用它。我不想让submethod运行,因为它会做危险的事情。

我完全不知道如何开始这件事。Mock的文档难以置信的难以理解,我甚至不知道该嘲笑什么或如何嘲笑它。

我如何模拟submethod函数,而将功能单独留在main_method中?


Tags: self语言objectmaindefargsjavamock
1条回答
网友
1楼 · 发布于 2024-05-29 04:26:10

我想你要找的是mock.patch.object

with mock.patch.object(MyClassUnderTest, "submethod") as submethod_mocked:
    submethod_mocked.return_value = 13
    MyClassUnderTest().main_method()
    submethod_mocked.assert_called_once_with(user_id, 100, self.context,
                                             self.account_type)

这是小描述

 patch.object(target, attribute, new=DEFAULT, 
              spec=None, create=False, spec_set=None, 
              autospec=None, new_callable=None, **kwargs)

patch the named member (attribute) on an object (target) with a mock object.

相关问题 更多 >

    热门问题