What is the difference between mocking and monkey patching?

Jad S picture Jad S · Jan 17, 2017 · Viewed 7.2k times · Source

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?

Answer

René Pijl picture René Pijl · Nov 3, 2017

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 test the 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.