There are two ways you can do this; with patch and with patch.object

Patch assumes that you are not directly importing the object but that it is being used by the object you are testing as in the following

#foo.py
def some_fn():
    return 'some_fn'

class Foo(object):
    def method_1(self):
        return some_fn()
#bar.py
import foo
class Bar(object):
    def method_2(self):
        tmp = foo.Foo()
        return tmp.method_1()
#test_case_1.py
import bar
from mock import patch

@patch('foo.some_fn')
def test_bar(mock_some_fn):
    mock_some_fn.return_value = 'test-val-1'
    tmp = bar.Bar()
    assert tmp.method_2() == 'test-val-1'
    mock_some_fn.return_value = 'test-val-2'
    assert tmp.method_2() == 'test-val-2'

If you are directly importing the module to be tested, you can use patch.object as follows:

#test_case_2.py
import foo
from mock import patch

@patch.object(foo, 'some_fn')
def test_foo(test_some_fn):
    test_some_fn.return_value = 'test-val-1'
    tmp = foo.Foo()
    assert tmp.method_1() == 'test-val-1'
    test_some_fn.return_value = 'test-val-2'
    assert tmp.method_1() == 'test-val-2'

In both cases some_fn will be 'un-mocked' after the test function is complete.

Edit: In order to mock multiple functions, just add more decorators to the function and add arguments to take in the extra parameters

@patch.object(foo, 'some_fn')
@patch.object(foo, 'other_fn')
def test_foo(test_other_fn, test_some_fn):
    ...

Note that the closer the decorator is to the function definition, the earlier it is in the parameter list.

Answer from Silfheed on Stack Overflow
🌐
Python
docs.python.org › 3 › library › unittest.mock-examples.html
unittest.mock — getting started
A common need in tests is to patch a class attribute or a module attribute, for example patching a builtin or patching a class in a module to test that it is instantiated. Modules and classes are effectively global, so patching on them has to ...
🌐
Linux find Examples
queirozf.com › entries › python-unittest-examples-mocking-and-patching
Python Unittest Examples: Mocking and Patching
November 26, 2022 - EXAMPLE: Application code (main.py) from myproject.helpers import complex_function def function_a(): return complex_function().upper() Test code: from unittest.mock import patch from myproject.main import function_a def test_called_patch(): with patch("myproject.main.complex_function") as ...
Discussions

unit testing - Using python's mock patch.object to change the return value of a method called within another method - Stack Overflow
Is it possible to mock a return value of a function called within another function I am trying to test? I would like the mocked method (which will be called in many methods I'm testing) to returned... More on stackoverflow.com
🌐 stackoverflow.com
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
Need help with requests and Mock in pytest
You don’t need to mock the TextIOWrapper. I’m on mobile, and am more familiar with using pytest’s monkeypatch object to patch, so bear with the total API change here. Also the code probably works, but again, on mobile. @pytest.fixture def mock_get_response(): with open(your_file_path) as f: return f.read() def test_num_pages(monkeypatch, mock_get_response): mock_get = Mock(return_value=Mock(text=mock_get_response)) mock_requests = Mock(get=mock_get) monkeypatch.setattr(“data_fetcher.requests”, mock_requests) # your code here This is a surprisingly complicated topic. At a high level, you want to be able to unit test your code without touching the real site, which is great and how mocking works. However, at some point, you want to test your code works with something that mirrors the behavior of the real thing. This can be the real thing, or people build “fakes”. The purpose of a fake is to still not be real, but to test some area of business logic around the external resource. A good example is if you’re interfacing with Twitter, a fake would error out if you try to read a tweet that didn’t exist, but would succeed if you publish a tweet then attempt to read it back. However, at some point, you typically do want to do some automated testing against the real thing (usually called integration testing). This should be after all of the other testing, because you don’t want to keep hitting external resources if you know your other tests don’t pass. EDIT: Apparently I have no idea how reddit markdown works because 4 spaces won't make it a codeblock :/ More on reddit.com
🌐 r/learnpython
4
5
December 7, 2020
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
🌐
Python
docs.python.org › 3 › library › unittest.mock.html
unittest.mock — mock object library
Auto-speccing can be done through the autospec argument to patch, or the create_autospec() function. Auto-speccing creates mock objects that have the same attributes and methods as the objects they are replacing, and any functions and methods (including constructors) have the same call signature as the real object. This ensures that your mocks will fail in the same way as your production code if they are used incorrectly: >>> from unittest.mock import create_autospec >>> def function(a, b, c): ...
🌐
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 used in a with statement, patch creates a temporary mock for the duration of the block, automatically cleaning up afterward. ... from unittest.mock import patch # sample test1 @patch('module.ClassName') def test_using_decorator(mock_class): mock_class.return_value.method.return_value = 'mocked value' assert mock_class().method() == 'mocked value' # sample test2 def test_using_context_manager(): with patch('module.ClassName') as mock_class: mock_class.return_value.method.return_value = 'mocked value' assert mock_class().method() == 'mocked value'
🌐
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 - To be specific, if your target function has m behaviors and n dependencies that need to be mocked out, then the number of the patch decorators that practically do the same thing will be m x n. Just for a single function, it’ll create a monstrosity similar to this: # src.py from unittest.mock import patch ...
🌐
Python Tutorial
pythontutorial.net › home › python unit testing › python patch()
Python patch() - Replace a Target with a Mock Object
July 9, 2022 - The following example illustrates how to use the patch() as a context manager: import unittest from unittest.mock import patch import total class TestTotal(unittest.TestCase): def test_calculate_total(self): with patch('total.read') as mock_read: mock_read.return_value = [1, 2, 3] result = ...
🌐
Medium
medium.com › @utkarshshukla.author › mastering-patching-and-mocking-in-python-a-comprehensive-guide-01f57fb91dda
Mastering Patching and Mocking in Python: A Comprehensive Guide | by Utkarsh Shukla | Medium
April 24, 2025 - Instead of making actual API calls during testing, we can patch the function to return predefined responses. Here’s a detailed example using the popular testing library, `unittest`: import unittest from unittest.mock import patch from my_module import function_to_test class TestFunction(unittest.TestCase): @patch('my_module.external_api_call') def test_function_with_mock(self, mock_external_api): mock_external_api.return_value = {'key': 'value'} result = function_to_test() self.assertEqual(result, expected_result)
Find elsewhere
🌐
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 - Now, let's say that instead of checking that x and y are within certain range, we want in our test to compare to exact values of x and y. In this example it's less obvious why we would want that, but in real life we often want to remove any randomness from our tests. In order to achieve that, we need to mock the randint method, so that it always returns the same value. We decided to use the patch decorator from mock library to achieve it.
Top answer
1 of 4
248

There are two ways you can do this; with patch and with patch.object

Patch assumes that you are not directly importing the object but that it is being used by the object you are testing as in the following

#foo.py
def some_fn():
    return 'some_fn'

class Foo(object):
    def method_1(self):
        return some_fn()
#bar.py
import foo
class Bar(object):
    def method_2(self):
        tmp = foo.Foo()
        return tmp.method_1()
#test_case_1.py
import bar
from mock import patch

@patch('foo.some_fn')
def test_bar(mock_some_fn):
    mock_some_fn.return_value = 'test-val-1'
    tmp = bar.Bar()
    assert tmp.method_2() == 'test-val-1'
    mock_some_fn.return_value = 'test-val-2'
    assert tmp.method_2() == 'test-val-2'

If you are directly importing the module to be tested, you can use patch.object as follows:

#test_case_2.py
import foo
from mock import patch

@patch.object(foo, 'some_fn')
def test_foo(test_some_fn):
    test_some_fn.return_value = 'test-val-1'
    tmp = foo.Foo()
    assert tmp.method_1() == 'test-val-1'
    test_some_fn.return_value = 'test-val-2'
    assert tmp.method_1() == 'test-val-2'

In both cases some_fn will be 'un-mocked' after the test function is complete.

Edit: In order to mock multiple functions, just add more decorators to the function and add arguments to take in the extra parameters

@patch.object(foo, 'some_fn')
@patch.object(foo, 'other_fn')
def test_foo(test_other_fn, test_some_fn):
    ...

Note that the closer the decorator is to the function definition, the earlier it is in the parameter list.

2 of 4
60

This can be done with something like this:

# foo.py
class Foo:
    def method_1():
        results = uses_some_other_method()


# testing.py
from mock import patch

@patch('Foo.uses_some_other_method', return_value="specific_value"):
def test_some_other_method(mock_some_other_method):
    foo = Foo()
    the_value = foo.method_1()
    assert the_value == "specific_value"

Here's a source that you can read: Patching in the wrong place

🌐
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
🌐
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 import patch @patch(target, new=MockObject) def test_something(mock): # Test code here
🌐
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
🌐
Real Python
realpython.com › python-mock-library
Understanding the Python Mock Object Library – Real Python
May 29, 2026 - So far, you’ve used mocks as arguments to functions or patching objects in the same module as your tests. Next, you’ll learn how to substitute your mocks for real objects in other modules. The unittest.mock library provides a powerful mechanism for mocking objects, called patch(), which looks up an object in a given module and replaces that object with a Mock.
🌐
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 ...
🌐
DevGenius
blog.devgenius.io › exploring-unittest-mock-a-comprehensive-overview-b8143c42cf3f
Python Mock Unit Testing Guide: A Comprehensive Exploration | by Brian | Dev Genius
March 10, 2024 - The behavior remains consistent, and the test will still pass as expected. import database_utils from unittest.mock import MagicMock, patch # Create a MagicMock object to mock the database query function mock_db_query = MagicMock() # Specify ...
🌐
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 - Python provides the unittest module, that allows you to write unit tests to check the behaviour of your functions and classes. However, your code often interacts with external dependencies like databases, APIs, or third-party libraries. You need to isolate your code from these external factors to create meaningful unit tests in such scenarios. This is where mocking and patching come into play.
🌐
Bright Yellow
ines-panker.com › 2020 › 06 › 01 › python-mock.html
Cheat Sheet of Python Mock by Ines Panker
June 1, 2020 - Here’s our code example: # my_app/services.py from my_app.clients import slack_client def notify_user(user): slack_client.send_message(user.slack_id, "Hello!") We want to test notify_user(). Its input is user, but we need to mock slack_client. We write the test with @patch(<path-to-slack_client>): from unittest.mock import patch # here @patch("my_app.services.slack_client") def test_notify_user(mock_slack): notify_user(some_user) mock_slack.send_message.assert_called_once() The path in patch has to be the full path to the relative!
🌐
Fugue
fugue.co › blog › 2016-02-11-python-mocking-101
Python Mocking 101: Fake It Before You Make It
February 10, 2018 - For example, if we're patching a call to requests.get, an HTTP library call, we can define a response to that call that will be returned when the API call is made in the function under test, rather than ensuring that a test server is available to return the desired response.
🌐
Toptal
toptal.com › python › an-introduction-to-mocking-in-python
Python Mocking: A Guide to Better Unit Tests | Toptal®
May 19, 2026 - For example: perhaps we’re writing a Slack integration and want to test out our new ‘Post to Slack’ feature, but don’t want to actually post to Slack every time we run our test suite. The Python unittest library includes a subpackage named unittest.mock which provides extremely powerful and useful means by which to mock and stub out these undesired side-effects.
🌐
DEV Community
dev.to › lizzzzz › mock-it-till-you-make-it-mocking-in-pythons-unittest-42d4
Mock It Till You Make It: Mocking in Python's unittest - DEV Community
April 29, 2024 - If a Mock object is a ball of clay we can shape, a MagicMock object is a ball of clay that comes with a set of moulds we can use to shape it. ... “patch() acts as a function decorator, class decorator or a context manager.