我熟悉其他语言中的其他模拟库,例如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
功能?
答案 0 :(得分:31)
我认为你要找的是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)
使用模拟对象修补对象(目标)上的命名成员(属性)。