What is the difference between mocking and monkey patching? What is the difference between mocking and monkey patching? python python

What is the difference between mocking and monkey patching?


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:

  • It keeps record of how mock objects are being called, so you can testthe calling behaviour 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), raise specific exceptions (side_effect).
  • Mocking of 'magic methds' (e.g. __str__).

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.