使用official documentation's Quick Guide中的示例,我尝试实现模拟。我试图嘲笑vocalize()
方法并让它返回"Meow, Meow!"
。这是我尝试过的:
import mock
class AnimalFactory:
def vocalize(self):
return "Woof, Woof!"
def build_animal_factory():
a = AnimalFactory()
sounds = a.vocalize()
print sounds
def main():
instance = AnimalFactory()
instance.vocalize = mock.MagicMock(return_value='Meow, Meow!')
build_animal_factory()
main()
运行此命令将输出:
$ python /var/tmp/mock_test.py
Woof, Woof!
我猜测模拟方法只存在于main()
的范围内。如何使模拟方法影响build_animal_factory()
函数?
更新
根据链接的答案,我通过将main()
方法更改为:
@mock.patch.object(AnimalFactory, 'vocalize')
def main(mocked_method):
mocked_method.return_value = 'Meow, Meow!'
build_animal_factory()