Mocking VS Monkey Patching in Python
What is Monkey Patching?
Monkey patching is a concept python where in we can change the behavior or work of code, module, or class at run time without changing the whole code base. For example in big projects, we have some third-party modules which may or may not be working while you are developing. In order to test our piece of code, we can tweak the behavior of that module.
#test_monkey.py class A: def func(self): print('I am method in class A') import test_monkey def monkey_func(self): print('Hi I am monkey method') test_monkey.A.func = monkey obj = test_monkey.A() obj.func()
Output
Hi I am monkey method
What is Mocking?
Mocking is defined as the set of different types of techniques that help achieve the goal of isolating units or pieces of code to test them independently while simulating the environment in which the unit of code exists.
In simple terms, mocking helps developers test a unit of code that may have dependencies on others. For example, I am implementing a caching layer over my database layer, which includes writing code to get/set data from/to Redis before performing any database operations to test this functionality. I don’t actually need to set/get data to/from Redis I can create a mock function that will create the illusion that I am able to get/set data to Redis.
Want to learn more about mocking and its techniques, check this link.
How is mocking different from monkey patching?
Monkey patching replaces a function/method/class with another at runtime for testing purposes, fixing a bug, or otherwise changing behavior. On the other hand, mocking uses monkey patching to replace part of your software under test with mock objects. It provides more functionality to write unit tests, such as:
- It records how mock objects are being called, so you can test the calling behavior of your code with asserts.
- A handy decorator patch() for the actual monkey patching.
- You can make mock objects to return specific values (return_value), and raise specific exceptions (side_effect).
Conclusion
Hope this blog helps you understand the basics of Monkey Patching and Mocking and also helps you in understanding the difference or use case of mocking and monkey patching. For more details on Monkey Patching and Mocking please refer link.