在对象上仅模拟一个方法
我熟悉其他语言的其他模拟库,例如Java中的Mockito,但是Python的mock
库使我的生活变得混乱。
我有以下课程想测试。
class MyClassUnderTest(object):
def submethod(self, *args):
do_dangerous_things()
def main_method(self):
self.submethod("Nothing.")
在我的测试中,我想确保submethod
在main_method
执行时调用了,并使用正确的参数调用了它。我不想submethod
跑步,因为它会做危险的事情。
我完全不确定该如何开始。Mock的文档难以理解,而且我不确定该模拟什么或如何模拟它。
submethod
在main_method
单独保留功能的同时,如何模拟该功能?
-
我想你要找的是
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)
使用模拟对象在对象(目标)上修补命名成员(属性)。