无论如何在Python模拟函数调用时打印语句?

时间:2015-03-07 17:39:05

标签: python python-3.x python-mock

我现在正在尝试使用mock.patch来模拟一个函数,例如:

with mock.patch.object(self.myClass, 'MyClassMethod', return_value=None) as mock_MyMethod:
    self.myClass.start()
    mock_MyMethod.assert_called_once_with()

现在我想让MyClassMethod打印“hello word !!”当它被调用。任何人都可以帮我找到解决方案。

提前致谢,

1 个答案:

答案 0 :(得分:3)

您可以使用side_effect。首先定义打印功能:

def hello():
    print("hello world!!!")
    return mock.DEFAULT

然后你像这样初始化你的模拟对象:

with mock.patch.object(..., side_effect=hello)
相关问题