56

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 "monkey patching" or in what seem to be very similar scenarios.

Is there any difference between the two concepts?

René Pijl
  • 4,310
  • 1
  • 19
  • 25
Jad S
  • 2,705
  • 6
  • 29
  • 49
  • 2
    This is a related answer https://github.com/pytest-dev/pytest/issues/4576#issuecomment-449864333 – foxiris Mar 18 '19 at 05:59

1 Answers1

38

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.

René Pijl
  • 4,310
  • 1
  • 19
  • 25
  • 23
    So then are `monkey-patching` and `mock`ing essentially the same? – WestCoastProjects May 28 '19 at 23:05
  • 9
    Sort of... there may be some confusion on the concept of a mock and the mock library. As mentioned, `monkey-patching` is the concept of switching some functionality out for another to facilitate testing. The `mock` is the thing that you `monkey-patch` with to replace the original functionality. The `mock library` gives you an object you can use to `monkey-patch`. The `mock` object from the `mock library` also gives you excellent features out of the box that helps you test that the mock behaves a certain way. – Luis Meraz Apr 12 '20 at 19:36
  • 3
    See also [@anthony-sottile](https://stackoverflow.com/users/812183/anthony-sottile)'s [post](https://github.com/pytest-dev/pytest/issues/4576#issuecomment-449864333) to learn more about `monkeypatch` vs `mock` comparison. – patryk.beza Nov 04 '21 at 17:42