I'm not completely sure if I understood your question, but I'll give it a try. As described in the documentation, Mock objects (actually MagickMock instances) are created by using the patch decorator:

from unittest.mock import patch

@patch('some_module.some_object')
def test_something(mocked_object):
    print(mocked_object)

This gives something like:

<MagicMock name='some_object' id='1870192381512'>

This is eqivalent to:

def test_something():
    with patch('some_module.some_object') as mocked_object:
        print(mocked_object)

This gives you the possibility to replace any object by a mock object to avoid calling the actual production code and/or to check how the original object is called (if the object is a function). The reason why using patch (or some similar methods) is preferred is that this ensures that the patch is reverted after the test (or after the context manager scope in the second case), so there are no side effects on other tests or other code.

To cite the documentation:

The patch decorators are used for patching objects only within the scope of the function they decorate. They automatically handle the unpatching for you, even if exceptions are raised. All of these functions can also be used in with statements or as class decorators.

You are also able to create a Mock object manually and assign it to an object - I assume this is what you mean in your question. If you do this instead of using patch, you are responsible to reset the previous state yourself. As this is more error-prone, I would advice to the dedicated methods for patching if possible.

Where this does not matter is in local objects and other mocks. Mocking local objects is seldom needed, but Mock instances are often created in conjunction with patching an object to preserve the instance of a mock object for later check:

@mock.patch('my_functions.MyClass')
def test_object(mock_class):
    arg1 = Mock()
    arg2 = Mock()
    do_something(arg1, arg2)

    # check that do_something creates MyClass with the given arguments 
    mock_class.assert_called_with(arg1, arg2)

In this case the case will only be used as an argument to a mock object, so no reset is needed.

To summarize:

  • patch is a convenience decorator/context manager function to replace objects with mock objects (or other objects) and reset the previous state after finishing or in case of an exception
  • Mock or derived objects are created by mock.patch, and can also be created manually. Manually created mocks are usually only used to patch local functions or other mocks where no reset is needed.
Answer from MrBean Bremen on Stack Overflow
🌐
Python
docs.python.org › 3 › library › unittest.mock.html
unittest.mock — mock object library
Additionally, mock provides a patch() decorator that handles patching module and class level attributes within the scope of a test, along with sentinel for creating unique objects.
🌐
Real Python
realpython.com › python-mock-library
Understanding the Python Mock Object Library – Real Python
May 29, 2026 - You create mock objects to replace real ones in your tests, ensuring that your tests are isolated. The Mock class allows you to imitate real objects, and the patch() function lets you temporarily substitute mocks for real objects in your tests.
Discussions

python - What is the difference between using mock.Mock() vs mock.patch(), and when to use one over the other? - Stack Overflow
There are a lot of old answers on this site saying Mock is preferred over patch with no mention of why. Maybe that's old python2 wisdom? The current unittest docs seem to suggest what you say above: patch is preferred over Mock (though the interface is weirder; Mock is simpler to use) ... More on stackoverflow.com
🌐 stackoverflow.com
What is mock and patch() for writing python unit tests ? Explain me like I'm 5 please?
There's a pretty good explanation here: https://realpython.com/python-mock-library And are you really sure that you need mock/patch for your unit test? What kind of program are you writing tests for? More on reddit.com
🌐 r/learnpython
4
3
March 31, 2021
Can someone ELI5 unittest.mock.patch()?
Tests should, usually, be as side-effects free as possible. This means that if you're testing methodA but to do so you need to use CrazyLibraryBinside your testing, you're probably setting yourself up to failure because you're not actually testing methodA you're testing methodA + CrazyLibraryB and you do not want that since, like we know, tests should be as isolated as possible This issue is exactly what mock helps you with. You can create Mock objects that will act as a proxy for, in our case, CrazyLibraryB, so you can setup a test for methodA that no longer depends on whatever CrazyLibraryB does More on reddit.com
🌐 r/learnpython
6
6
January 2, 2019
Is there a way to mock a script which does not have functions or classes
I don't see the relevance of whether or not the script under test has functions. The thing you want to mock is a method of class a, which you can easily patch. More on reddit.com
🌐 r/learnpython
13
2
July 15, 2024
🌐
Medium
medium.com › @tankoraphael › understanding-the-patch-function-in-pythons-unittest-mock-library-5d98952fc17a
Understanding the Patch Function in Python’s unittest.mock Library | by Tankoraphael | Medium
December 20, 2024 - The patch function can be used in two primary ways: a. As a Decorator: When applied as a decorator, patch modifies the function it decorates, replacing specified attributes with mocks for the duration of the test. b. As a Context Manager: When ...
🌐
Linux find Examples
queirozf.com › entries › python-unittest-examples-mocking-and-patching
Python Unittest Examples: Mocking and Patching
November 26, 2022 - from unittest.mock import Mock # this function takes an object as argument and calls a # method on it def function_with_call(some_obj, argument): return some_obj.some_method(argument) def test_called(): mock = Mock() mock.some_method = Mock(return_value=None) function_with_call(mock, "foo bar") # will return true if method was called one or more times mock.some_method.assert_called() Use of assert_not_called() to assert it was not called · Use patch(...) and assert_called() to assert that a pacthed function was called.
Top answer
1 of 1
24

I'm not completely sure if I understood your question, but I'll give it a try. As described in the documentation, Mock objects (actually MagickMock instances) are created by using the patch decorator:

from unittest.mock import patch

@patch('some_module.some_object')
def test_something(mocked_object):
    print(mocked_object)

This gives something like:

<MagicMock name='some_object' id='1870192381512'>

This is eqivalent to:

def test_something():
    with patch('some_module.some_object') as mocked_object:
        print(mocked_object)

This gives you the possibility to replace any object by a mock object to avoid calling the actual production code and/or to check how the original object is called (if the object is a function). The reason why using patch (or some similar methods) is preferred is that this ensures that the patch is reverted after the test (or after the context manager scope in the second case), so there are no side effects on other tests or other code.

To cite the documentation:

The patch decorators are used for patching objects only within the scope of the function they decorate. They automatically handle the unpatching for you, even if exceptions are raised. All of these functions can also be used in with statements or as class decorators.

You are also able to create a Mock object manually and assign it to an object - I assume this is what you mean in your question. If you do this instead of using patch, you are responsible to reset the previous state yourself. As this is more error-prone, I would advice to the dedicated methods for patching if possible.

Where this does not matter is in local objects and other mocks. Mocking local objects is seldom needed, but Mock instances are often created in conjunction with patching an object to preserve the instance of a mock object for later check:

@mock.patch('my_functions.MyClass')
def test_object(mock_class):
    arg1 = Mock()
    arg2 = Mock()
    do_something(arg1, arg2)

    # check that do_something creates MyClass with the given arguments 
    mock_class.assert_called_with(arg1, arg2)

In this case the case will only be used as an argument to a mock object, so no reset is needed.

To summarize:

  • patch is a convenience decorator/context manager function to replace objects with mock objects (or other objects) and reset the previous state after finishing or in case of an exception
  • Mock or derived objects are created by mock.patch, and can also be created manually. Manually created mocks are usually only used to patch local functions or other mocks where no reset is needed.
🌐
Python
docs.python.org › 3 › library › unittest.mock-examples.html
unittest.mock — getting started
This means you access the “mock ... some_function that instantiates Foo and calls a method on it. The call to patch() replaces the class Foo with a mock....
🌐
Medium
medium.com › @reetesh043 › understanding-patch-decorators-in-pythons-unittest-framework-e802b2aa6f6d
Understanding Patch Decorators in Python’s unittest Framework | by Reetesh Kumar | Medium
August 10, 2024 - It temporarily replaces the target object with a mock during the test scope, automatically restoring the original object once the test is complete. The patch decorator can be used in several ways, but the basic syntax is: from unittest.mock ...
Find elsewhere
🌐
Reddit
reddit.com › r/learnpython › what is mock and patch() for writing python unit tests ? explain me like i'm 5 please?
r/learnpython on Reddit: What is mock and patch() for writing python unit tests ? Explain me like I'm 5 please?
March 31, 2021 -

I am writing a unit test for the first time and I am supposed to figure this out by my self. I am utterly confused cuz I dont know the first thing about writing a unit test. Especially mock and patch().

  1. What is it?

  2. Why do we use it ?

  3. What is the difference between mock and patch?

I've tried reading documentations on python website(https://docs.python.org/3/library/unittest.mock.html) , tried watching youtube videos( after which I feel a little familiarized. But it is still useless for me ). I really feel stuck right now. :(

Also, any resource that could help this noob write better unit tests would be greatly appreciated.

🌐
Rednafi
rednafi.com › home › python › patching test dependencies via pytest fixture & unittest mock
Patching test dependencies via pytest fixture & unittest mock | Redowan's Reflections
June 30, 2026 - Combine pytest fixtures with unittest.mock.patch for clean, reusable test mocking patterns that integrate seamlessly with pytest's ecosystem.
🌐
Pytest with Eric
pytest-with-eric.com › mocking › mocking-vs-patching
Mocking Vs. Patching (A Quick Guide For Beginners) | Pytest with Eric
March 23, 2026 - Use tools that automatically unpatch or restore the original state of the object after each test to prevent side effects - Pytest fixtures with setup teardown, monkeypatch fixture or unittest.mock.patch fixtures.
🌐
DEV Community
dev.to › tanyatik › how-to-patch-python-objects-in-tests-3mpb
How to patch Python objects in tests - DEV Community
June 28, 2022 - from mock import patch @patch('random.randint', return_value=59) def test_create_point(_): point = create_random_point() assert point.x == 59 assert point.y == 59 · However, if you try this, you will see that it doesn't work: So the question is, of course: why it doesn't work? Actually, Python's unittest.mock library documentation provides us with an answer, but it might be a bit hard to understand at first.
🌐
YouTube
youtube.com › redshiftzero
How to use Python's unittest.mock.patch - YouTube
How to use (and where to apply) Python's unittest.mock.patch in your test suites. In this video I show where to patch, and three ways of applying mock.patch:...
Published: December 1, 2019
Views: 11K
🌐
Medium
mike-diaz006.medium.com › what-i-learned-at-work-this-week-pytest-patch-ff84806aacbe
What I Learned at Work this Week: python patch | by Mike Diaz | Medium
March 19, 2023 - Ideally, we’d want to avoid those processes while testing and, according to the same Real Python article, this is where we’d want to use patch: “[patch] looks up an object in a given module and replaces that object with a Mock.” Here’s the code that worked for me: from unittest.mock import patch from python_practice import function_one @patch('python_practice.complex_function', return_value='banana') def test_function_one(self): # setup expected_result = 'the patch worked' # act actual_result = function_one() #verify assert actual_result == expected_result
🌐
Reddit
reddit.com › r/learnpython › can someone eli5 unittest.mock.patch()?
r/learnpython on Reddit: Can someone ELI5 unittest.mock.patch()?
January 2, 2019 -

I'm a QA at a startup learning python for some backend test automation. Super newb to python and coding in general beyond UI testing with Android

I'm taking Udemy's "Automated Testing in Python" course to dive deep into things and the teacher just introduced "patching" methods and I'm having some trouble wrapping my head around what this actually does (also, why I might want to use them. He seemed to stress wrapping my head around it since it will be used a lot throughout the course.

Can someone give in ELI5? The docs are somewhat obscure is all. Thanks so much!

Top answer
1 of 3
4
In short, it lets you fake functions, methods, classes, etc., that you can't or don't want to test. Rather than try to explain lots of details I'll give you an example: @mock.patch('foo_service.fetch') def test_foo_service(self, mock_fetch): mock_fetch.side_effect = lambda url: self.fake_data[url] Assume this method is on a test class, and pretend we have some service "foo" that makes external requests to an API with the fetch method. Also pretend we defined fake_data as a mapping from URLs to sample response payloads. In the above code, the decorator is replacing fetch with a magic mock object and passing it to our test method. Whenever fetch is used, our mock will be used instead of the real method. Once you have this mock, there's tons of stuff you can do with it. What the above code would do is call the function we created (that's what side_effect does, there's also return_value for simpler cases). This is one instance where our patch is very useful, because we can define fake data for unit testing instead of making external requests (This is bad, you want your tests to be constant. The API could change, the response could change, etc.). Let me know if you have further questions or if this doesn't make sense. I found mocks hard to wrap my head around for a while, but just think of it as an empty placeholder. You can make it do whatever you want and you can also test against it (has it been called? How many times? With what arguments?).
2 of 3
3
Tests should, usually, be as side-effects free as possible. This means that if you're testing methodA but to do so you need to use CrazyLibraryBinside your testing, you're probably setting yourself up to failure because you're not actually testing methodA you're testing methodA + CrazyLibraryB and you do not want that since, like we know, tests should be as isolated as possible This issue is exactly what mock helps you with. You can create Mock objects that will act as a proxy for, in our case, CrazyLibraryB, so you can setup a test for methodA that no longer depends on whatever CrazyLibraryB does
🌐
CodeFatherTech
codefather.tech › home › blog › mastering python mock and patch: mocking for unit testing
Mastering Python Mock and Patch: Mocking For Unit Testing
December 8, 2024 - To recap, we have seen how to replace a function in a Python module with a MagicMock object as part of a unit test. The unittest.mock library provides the patch function (unittest.mock.patch) that can replace the behavior of a target (a function, a method, or a class) as part of unit tests.
🌐
Medium
medium.com › @kundansingh0619 › python-testcase-2-unittest-mock-patch-and-magicmock-f08095b120f1
Python TestCase_2 : Unittest.mock ,patch and magicmock | by Kundan Singh | Medium
January 7, 2025 - import unittest from unittest.mock import patch, Mock import requests # A simple function that makes an HTTP GET request def fetch_data(url): try: response = requests.get(url) if response.status_code == 200: return response.json() elif response.status_code == 404: return {"error": "Not Found"} else: return {"error": "Server Error"} except requests.exceptions.RequestException as e: return {"error": "Request failed", "details": str(e)} import unittest from unittest.mock import patch, Mock import requests class TestFetchData(unittest.TestCase): def test_fetch_data_success(self): with patch('reque
🌐
GitHub
github.com › python › cpython › blob › main › Lib › unittest › mock.py
cpython/Lib/unittest/mock.py at main · python/cpython
By default this is `test`, which matches the way `unittest` finds tests. You can specify an alternative prefix by setting `patch.TEST_PREFIX`. · Patch can be used as a context manager, with the with statement. Here the · patching applies to the indented block after the with statement. If you · use "as" then the patched object will be bound to the name after the · "as"; very useful if `patch` is creating a mock object for you.
Author: python
🌐
Python Tutorial
pythontutorial.net › home › python unit testing › python patch()
Python patch() - Replace a Target with a Mock Object
July 9, 2022 - Summary: in this tutorial, you’ll learn how to use the Python patch() to replace a target with a mock object temporarily. The unittest.mock module has a patch() that allows you to temporarily replace a target with a mock object.
🌐
Medium
datageeks.medium.com › python-unittest-a-guide-to-patching-mocking-and-magicmocks-40f2c0738981
Python Unittest: A Guide to Patching, Mocking, and MagicMocks | by DataGeeks | Medium
December 12, 2023 - Setting Up the Environment: Before diving into unit testing, ensure you have a suitable environment set up. You should have Python installed, and you may want to create a virtual environment to manage dependencies. You’ll also need the unittest.mock module, which is included in Python 3.3 and later.
🌐
Runebook.dev
runebook.dev › en › docs › python › library › test › test.support.patch
A Friendly Guide to Python's unittest.mock.patch(): Avoiding the Wrong Target
First off, it's important to know that test.support.patch() is a utility mainly used within Python's own internal test suite, not typically for general user testing. For almost all user-level testing in Python, you should be using the standard and more powerful unittest.mock.patch() from the unittest.mock library, which is part of Python's standard library.