Python 仅模拟对象上的单个方法

Python 仅模拟对象上的单个方法,python,mocking,python-mock,Python,Mocking,Python Mock,我熟悉其他语言中的其他模拟库,比如Java中的Mockito,但是Python的mock库把我的生活弄糊涂了 我有下面一节课要考 class MyClassUnderTest(object): def submethod(self, *args): do_dangerous_things() def main_method(self): self.submethod("Nothing.") 在我的测试中,我希望确保在执行main_方法时调用了su

我熟悉其他语言中的其他模拟库,比如Java中的Mockito,但是Python的
mock
库把我的生活弄糊涂了

我有下面一节课要考

class MyClassUnderTest(object):

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

    def main_method(self):
       self.submethod("Nothing.")
在我的测试中,我希望确保在执行
main_方法
时调用了
submethod
,并且使用正确的参数调用了它。我不想运行
submethod
,因为它会做危险的事情

我完全不确定该如何开始。Mock的文档令人难以置信地难以理解,我甚至不知道该模仿什么或如何模仿它


如何模拟
子方法
函数,而将功能单独保留在
main\u方法
中?

我想您要找的是
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)
用模拟对象修补对象(目标)上的命名成员(属性)


谢谢,由于某种原因,我一直很难理解所有不同的
补丁
方法以及如何使用它们。