🌐
Python
docs.python.org › 3 › library › unittest.mock.html
unittest.mock — mock object library
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): ...
🌐
Python
docs.python.org › 3 › library › unittest.mock-examples.html
unittest.mock — getting started
In this example we’re using another mock to store the arguments so that we can use the mock methods for doing the assertion. Again a helper function sets this up for us. >>> from copy import deepcopy >>> from unittest.mock import Mock, patch, DEFAULT >>> def copy_call_args(mock): ...
Discussions

unit testing - How to properly use mock in python with unittest setUp - Stack Overflow
In my attempt to learn TDD, trying to learn unit testing and using mock with python. Slowly getting the hang of it, but unsure if I'm doing this correctly. Forewarned: I'm stucking using python 2.4 because the vendor API's come as pre-compiled 2.4 pyc files, so I'm using mock 0.8.0 and unittest ( ... More on stackoverflow.com
🌐 stackoverflow.com
Stuck with unittest as the method returns mock object.
But mock_self is just a mock. You never call your actual code, you only ever call the mock, which naturally returns a mock. MyClass isn't even imported in your test file. More on reddit.com
🌐 r/learnpython
6
1
February 19, 2025
Please explain unittest.mock
unittest.mock is a package that allows you to swap out an object for a mock object instead. You do this when there is code in your test that you don't want to run. For example, say that I have a function that, amongst other things, goes to a database and gets some data. When I create a test for this function, I don't want the function to go to the database. One reason is that it will slow the test down. Any connection to something external is usually something that slows down code. A second reason is that the content of the database may not be under my control and might change - I don't want my tests to fail just because someone added or deleted data from the database. This is where unittest.mock comes in. I can replace the database call with a mock object that contains mocked-up data. When the function is running under test, at the point that it would go to the database and return a database object, the mock object would be returned instead. The data inside this mock object will always stay the same, and so the tests should always pass. unittest is the package that's used for unit testing in general. It lets you create tests and run them. You don't need to use a unit testing package when creating tests, but it's highly recommended to. Other testing packages are pytest and nose. You should see unittest and unittest.mock as being orthogonal to each other. You can create a test using unittest without using mock, in fact it's encouraged not to use mock unless you need to. And you can use unittest.mock without unittest, for example if you choose to create your own tests yourself or if you decide to use pytest for your testing framework instead. The patch decorator gives you an easy way to use mocks as described above. When you have a test method, simply use a decorator on that method, and supply a path to the object you want to mock. That object will be mocked for the lifetime of the test method. More on reddit.com
🌐 r/learnpython
3
1
January 9, 2019
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
People also ask

What is mocking in Python?
Mocking in Python means the unittest.mock library is being utilized to replace parts of the system with mock objects, allowing easier and more efficient unit testing than would otherwise be possible.
🌐
toptal.com
toptal.com › python › an-introduction-to-mocking-in-python
Python Mocking: A Guide to Better Unit Tests | Toptal®
What is mocking in unit testing?
Mocking simulates the existence and behavior of a real object, allowing software engineers to test code in various hypothetical scenarios without the need to resort to countless system calls. Mocking can thereby drastically improve the speed and efficiency of unit tests.
🌐
toptal.com
toptal.com › python › an-introduction-to-mocking-in-python
Python Mocking: A Guide to Better Unit Tests | Toptal®
🌐
Real Python
realpython.com › python-mock-library
Understanding the Python Mock Object Library – Real Python
May 29, 2026 - For example, if you misspell .assert_called() by instead typing .asst_called(), then your test won’t raise an AssertionError. This is because you’ve created a new method on the Python mock object named .asst_called() instead of evaluating an actual assertion. Note: Interestingly, the developers of unittest.mock handle a list of common misspellings of assert.
🌐
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 - Want to see it in action? Fire up Python in your terminal and execute the following: # Import the mock library from unittest.mock import Mock # Create a Mock integer object mock_number = Mock(1) # Try to add mock_number with another integer mock_number + 2
🌐
Medium
medium.com › @rohaangurunathrevankar › mocking-for-unit-tests-using-python-5e1fedde4f97
Mocking unit tests using python. Mocking in unittest in Python is a… | by Rohaan gurunath revankar | Medium
June 17, 2024 - import random from unittest.mock import Mock, patch class Employee: def __init__(self): self.skills = [] def add_skills(self, tech_name): name = tech_name.lower() if name not in self.skills: self.skills.append(name) return self def get_random_skill(self): return random.choice(self.skills) e = Employee() e.add_skills('python') e.add_skills('java') e.add_skills('sql') e.add_skills('aws') e.add_skills('django') e.add_skills('cpp') random.choice = Mock(return_value='python') print(e.get_random_skill())
🌐
Medium
medium.com › @moraneus › the-art-of-mocking-in-python-a-comprehensive-guide-8b619529458f
The Art of Mocking in Python: A Comprehensive Guide | by Moraneus | Medium
May 21, 2024 - The unittest.mock module, included in Python's standard library, provides a powerful and flexible way to create mock objects. Let's start with a basic. example of mocking an API Call.
🌐
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.
Find elsewhere
🌐
Linux find Examples
queirozf.com › entries › python-unittest-examples-mocking-and-patching
Python Unittest Examples: Mocking and Patching
November 26, 2022 - EXAMPLE: from unittest.mock import Mock def function_e(some_obj, argument): return some_obj.some_method(argument) def test_arguments(): mock = Mock() # mock object mock.some_method = Mock(return_value=None) # mock method function_e(mock, "foo bar") mock.some_method.assert_called() # arguments passed to method some_method arguments_tuple = mock.some_method.call_args[0] assert "foo bar" in arguments_tuple · Official docs for Python unittest module ·
🌐
Python Tutorial
pythontutorial.net › home › python unit testing › python unittest mock
Python Unittest Mock
July 9, 2022 - The following picture illustrates how the test works with mock objects: ... test_alert_normal (test_odometer.TestOdometer) ... ok ---------------------------------------------------------------------- Ran 1 test in 0.000s OKCode language: Python (python) The following adds the test cases that are over and under speed: import unittest from unittest.mock import Mock import odometer class TestOdometer(unittest.TestCase): def test_alert_normal(self): odometer.speed = Mock() odometer.speed.return_value = 70 self.assertFalse(odometer.alert()) def test_alert_overspeed(self): odometer.speed = Mock() odometer.speed.return_value = 100 self.assertFalse(odometer.alert()) def test_alert_underspeed(self): odometer.speed = Mock() odometer.speed.return_value = 59 self.assertTrue(odometer.alert())Code language: Python (python)
🌐
Better Stack
betterstack.com › community › guides › scaling-python › python-unittest-mock
Mastering unittest.mock in Python | Better Stack Community
April 7, 2025 - A Mock instance can stand in for any Python object, creating attributes and methods on demand as you access them. To create a basic mock object, you simply instantiate the Mock class: ... from unittest.mock import Mock # Create a basic mock object mock_object = Mock() # Call the mock as if it were a function result = mock_object() # Access attributes attribute = mock_object.some_attribute # Call methods method_result = mock_object.some_method(1, 2, 'three') print(f"Mock: {mock_object}") print(f"Result of calling mock: {result}") print(f"Attribute: {attribute}") print(f"Method result: {method_result}")
🌐
YouTube
youtube.com › watch
Python Mocking Tutorial: Unit Testing with unittest.mock for Beginners - YouTube
Learn Python mocking with unittest.mock! This beginner-friendly tutorial covers everything you need to know to write effective unit tests. We'll explore the ...
Published: April 2, 2025
🌐
Medium
medium.com › @alcaptar › unit-testing-in-python-how-to-effectively-use-mock-and-create-autospec-a3158d125dd8
Unit testing in Python: How to effectively use Mock and create_autospec | by Alejandro Capdevila | Medium
May 6, 2025 - The best thing to do is to wrap the call to the external library instead of mocking the library itself, and only check that we have called that wrapper. This way, we will be abstracting from the implementation details of that particular library, and we will prevent our tests from failing if any of those details change. In short, to do unit testing in Python, the best tool is to use create_autospec and enable the spec_set=True option to be sure that we are testing what we expect.
🌐
Jingwen Zheng
jingwen-z.github.io › how-to-apply-mock-with-python-unittest-module
How to apply mock with python unittest module? - Jingwen Zheng
July 16, 2020 - In the scripts google_place_api.py, I create a Python class named “Place”, which contains one place’s latitude, longitude, name, ID and its rating; then I create a function search_place(gps='gps', api_key='api_key') in order to get places’ information by Google Places API and inject the values into Place class. # learn_unittest_mock/google_place_api_test.py import unittest from unittest.mock import patch, Mock, call from requests.exceptions import Timeout import learn_unittest_mock.google_place_api as target class GooglePlaceApiTest(unittest.TestCase): def setUp(self): self.patcher = p
🌐
Semaphore
semaphore.io › home › getting started with mocking in python
Getting Started with Mocking in Python - Semaphore
April 22, 2021 - In our test, we want to mock out the unpredictable API call and only test that a Blog object’s posts method returns posts. We will need to patch all Blog objects’ posts methods as follows. from unittest import TestCase from unittest.mock import patch, Mock class TestBlog(TestCase): @patch('main.Blog') def test_blog_posts(self, MockBlog): blog = MockBlog() blog.posts.return_value = [ { 'userId': 1, 'id': 1, 'title': 'Test Title', 'body': 'Far out in the uncharted backwaters of the unfashionable end of the western spiral arm of the Galaxy\ lies a small unregarded yellow sun.'
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-mock-library
Python Mock Library: A Comprehensive Guide to Effective Testing - GeeksforGeeks
July 23, 2025 - To get started with the Mock Library, you need to import the unittest.mock module. This module provides the Mock class, which is the main building block for creating mock objects. You can create a mock object by instantiating the Mock class, like this: ... Once you have a mock object, you can set its behavior using various methods and attributes provided by the Mock Library. For example, you can specify return values for method calls, set attributes, and define side effects.
🌐
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 - In this example, we’ve replaced Mock with MagicMock while keeping the rest of the code the same. 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 the return value of the MagicMock object mock_db_query.return_value = {'user_id': 123, 'name': 'Jane Smith', 'email': 'jane@example.com'} # Use the mock object to replace the original function during testing with patch('database_utils.retrieve_user_info', mock_db_query): # Call the function under test user_info = database_utils.retrieve_user_info(123) # Assert that the function returned the expected user information assert user_info == {'user_id': 123, 'name': 'Jane Smith', 'email': 'jane@example.com'}
🌐
Medium
yeraydiazdiaz.medium.com › what-the-mock-cheatsheet-mocking-in-python-6a71db997832
What the mock? — A cheatsheet for mocking in Python | by Yeray Diaz | Medium
August 19, 2019 - The centerpoint of the unittest.mock module is, of course, the Mock class. The main characteristic of a Mock object is that it will return another Mock instance when: ... This is the default behaviour, but it can be overridden in different ways. For example you can assign a value to an attribute in the Mock by: Assign it directly, like you’d do with any Python object.
🌐
Testmu
testmu.ai › testmu ai › blog › getting started with python unittest.mock library
Getting Started With Python unittest.mock Library | TestMu AI (Formerly LambdaTest)
January 11, 2026 - An example will be an online store that uses a third-party payment gateway to process customers’ payments. A tester will mock the payment API in the test environment to simulate pending, failed or successful transactions. Python unittest.mock library is used for creating mock objects when it becomes impractical to test real objects.
Top answer
1 of 6
100

You can use patch() as a class decorator, not just as a function decorator. You can then pass in the mocked function as before:

@patch('mymodule.SomeClass')
class MyTest(TestCase):

    def test_one(self, MockSomeClass):
        self.assertIs(mymodule.SomeClass, MockSomeClass)

See: Applying the same patch to every test method (which also lists alternatives)

It makes more sense to set up the patcher this way on setUp if you want the patching to be done for all the test methods.

2 of 6
35

I'll start by answering your questions, and then I'll give a detailed example of how patch() and setUp() interact.

  1. I don't think it looks right, see my answer to question #3 in this list for details.
  2. Yes, the actual call to patch looks like it should mock the object you want.
  3. No, you almost never want to use the @patch() decorator on setUp(). You got lucky, because the object is created in setUp() and never gets created during the test method.
  4. I don't know of any way to make a mock object raise an exception without importing that exception into your test case file.
  5. I don't see any need for patch.object() here. It just lets you patch attributes of an object instead of specifying the target as a string.

To expand on my answer to question #3, the problem is that the patch() decorator only applies while the decorated function is running. As soon as setUp() returns, the patch is removed. In your case, that works, but I bet it would confuse someone looking at this test. If you really only want the patch to happen during setUp(), I would suggest using the with statement to make it obvious that the patch is going to be removed.

The following example has two test cases. TestPatchAsDecorator shows that decorating the class will apply the patch during the test method, but not during setUp(). TestPatchInSetUp shows how you can apply the patch so that it's in place during both setUp() and the test method. Calling self.addCleanUp() makes sure that the patch will be removed during tearDown().

import unittest
from mock import patch


@patch('__builtin__.sum', return_value=99)
class TestPatchAsDecorator(unittest.TestCase):
    def setUp(self):
        s = sum([1, 2, 3])

        self.assertEqual(6, s)

    def test_sum(self, mock_sum):
        s1 = sum([1, 2, 3])
        mock_sum.return_value = 42
        s2 = sum([1, 2, 3])

        self.assertEqual(99, s1)
        self.assertEqual(42, s2)


class TestPatchInSetUp(unittest.TestCase):
    def setUp(self):
        patcher = patch('__builtin__.sum', return_value=99)
        self.mock_sum = patcher.start()
        self.addCleanup(patcher.stop)

        s = sum([1, 2, 3])

        self.assertEqual(99, s)

    def test_sum(self):
        s1 = sum([1, 2, 3])
        self.mock_sum.return_value = 42
        s2 = sum([1, 2, 3])

        self.assertEqual(99, s1)
        self.assertEqual(42, s2)
🌐
AskPython
askpython.com › python › built-in-methods › mocking-in-python-unittestmock
Mocking in Python Using Unittest.mock - AskPython
February 2, 2023 - A side effect in Mock() object is always executed whenever a Mock() object is called. It can be of various types, such as executing a function, calling an Exception, referencing an iterable, etc. The following code demonstrates three different types of Side Effects. from unittest.mock import Mock mock1=Mock(side_effect=TypeError('something')) def plusone(x): return x+1 kv={'a':'alphabet','n':'number','s':'special character','c':'capital letters'} def keypairs(arg): return kv[arg] mock=Mock() mock2=Mock() mock.side_effect=plusone mock2.side_effect=keypairs print(mock(4)) print(mock2('a')) print(mock1())