在对象上仅模拟一个方法 [英] Mocking only a single method on an object

查看:70
本文介绍了在对象上仅模拟一个方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我熟悉其他语言的其他模拟库,例如Java中的Mockito,但是Python的mock库使我的生活变得混乱.

I'm familiar with other mocking libraries in other languages such as Mockito in Java, but Python's mock library confuses the life out of me.

我有以下课程要测试.

class MyClassUnderTest(object):

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

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

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

In my tests, I'd like to make sure that the submethod was called when main_method was executed and that it was called with the right arguments. I don't want submethod to run, as it does dangerous things.

我完全不确定该如何开始. Mock的文档难以理解,而且我不确定该模拟什么或如何模拟它.

I'm entirely unsure as to how to get started with this. Mock's documentation is incredibly hard to understand and I'm not sure what to even mock or how to mock it.

如何在不使用main_method的情况下模拟submethod函数?

How can I mock the submethod function, while leaving the functionality in main_method alone?

推荐答案

我认为您正在寻找的是mock.patch.object

I think what you are looking for is 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.

这篇关于在对象上仅模拟一个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆