这是我的班级:
class GoogleCloudLayer:
def deleteMachine(self, machineName):
return machineName + ' is dead. (stubbed)'
有效:
>>> gc = GoogleCloudLayer()
>>> gc.deleteMachine('test')
test is dead (stubbed)
但是我想在测试中使用,我希望在其上定义assert_called_with
方法:
from mock import MagicMock
#Stubbing with itself just so it will have the `assert_called_with` method defined on it
GoogleCloudLayer.deleteMachine = MagicMock(side_effect = GoogleCloudLayer.deleteMachine)
但后来我
>>> gc = GoogleCloudLayer()
>>> gc.deleteMachine('test')
unbound method deleteMachine() must be called with GoogleCloudLayer instance as first argument (got str instance instead)
如果我将生产代码更改为gc.deleteMachine(gc, 'test')
则可行。
但是我们不想要那个,是吗?
答案 0 :(得分:1)
lambda
在这种情况下非常有用,请尝试:
GoogleCloudLayer.createMachine = MagicMock(side_effect = lambda *args, **kwargs: GoogleCloudLayer.createMachine)