当 Python 模拟函数被调用时,是否有打印语句?

Is there anyway to print a statement when Python mock function called?

我现在正在尝试使用 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!!"。谁能帮我找到解决方案。

提前致谢,

您可以使用 side_effect。首先定义打印函数:

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

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

with mock.patch.object(..., side_effect=hello)