Using the example in the official documentation's Quick Guide, I tried to implement mocking. I'm trying to mock the vocalize() method and have it return "Meow, Meow!". Here is what I've tried:
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()
Running this will output:
$ python /var/tmp/mock_test.py
Woof, Woof!
I'm guessing that the mocked method only exists in the scope of main(). How do I get the mocked method to affect the build_animal_factory() function?
Update
Based on the linked answer, I got it working by changing the main() method to:
@mock.patch.object(AnimalFactory, 'vocalize')
def main(mocked_method):
mocked_method.return_value = 'Meow, Meow!'
build_animal_factory()