这是我的类:
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')
它可以工作。但我们不想这样,是吗?
lambda
在这种情况下可能很有用,请尝试:
GoogleCloudLayer.createMachine = MagicMock(side_effect = lambda *args, **kwargs: GoogleCloudLayer.createMachine)