I work with python and I'm a bit new to testing. I often see tests replacing an external dependency with a local method like so:
import some_module
def get_file_data():
return "here is the pretend file data"
some_module.get_file_data = get_file_data
# proceed to test
I see this referred to as "monkey patching" as in the question. I also see the word "mock" being used a lot alongside "money patching" or in what seem to be very similar scenarios.
Is there any difference between the two concepts?
Monkey patching is replacing a function/method/class by another at runtime, for testing purpses, fixing a bug or otherwise changing behaviour.
The unittest.mock library makes use of monkey patching to replace part of your software under test by mock objects. It provides functionality for writing clever unittests, such as:
patch()
for the actual monkey patching.return_value
), raise specific exceptions (side_effect
).You can use mocking, for example, to replace network I/O (urllib, requests) in a client, so unittests work without depending on an external server.