58

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?

1

1 Answer 1

40

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.

3
  • 23
    So then are monkey-patching and mocking essentially the same? May 28, 2019 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, 2020 at 19:36
  • 3
    See also @anthony-sottile's post to learn more about monkeypatch vs mock comparison. Nov 4, 2021 at 17:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.