🌐
Python
docs.python.org › 3 › library › unittest.mock.html
unittest.mock — mock object library
Source code: Lib/unittest/mock.py unittest.mock is a library for testing in Python. It allows you to replace parts of your system under test with mock objects and make assertions about how they hav...
🌐
Python
docs.python.org › 3 › library › unittest.mock-examples.html
unittest.mock — getting started
Using Mock: Mock patching methods: Common uses for Mock objects include: Patching methods, Recording method calls on objects. You might want to replace a method on an object to check that it is cal...
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®
🌐
AskPython
askpython.com › python › built-in-methods › mocking-in-python-unittestmock
Mocking in Python Using Unittest.mock - AskPython
February 2, 2023 - The Mock() object available in Python unittest.mock module is a dynamic object and can mimic any library provided to it as an input. The object can also be declared as an individual object, without referencing any other library.
🌐
Real Python
realpython.com › python-mock-library
Understanding the Python Mock Object Library – Real Python
May 29, 2026 - Mocking in Python with unittest.mock allows you to simulate complex logic or unpredictable dependencies, such as responses from external services. You create mock objects to replace real ones in your tests, ensuring that your tests are isolated.
🌐
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 - For this tutorial, I am using Visual Studio Code’s Testing interface, however, you are encouraged to use whatever tools you are already familiar with. For help configuring the Python plugin to run your tests in VS Code, check out the documentation.
🌐
Better Stack
betterstack.com › community › guides › scaling-python › python-unittest-mock
Mastering unittest.mock in Python | Better Stack Community
April 7, 2025 - Python's unittest.mock library is a powerful tool for creating test doubles that simulate the behavior of real objects during testing.
🌐
Medium
medium.com › @reetesh043 › understanding-unittest-mock-the-python-mock-object-library-aaaded4ddf98
Understanding unittest.mock — The Python Mock Object Library | by Reetesh Kumar | Medium
August 10, 2024 - The unittest.mock library is essential for Python developers who write unit tests. It allows you to simulate parts of your system, assert their usage, and isolate the code under test from external dependencies.
🌐
Python
docs.python.org › 3.9 › library › unittest.mock.html
unittest.mock — mock object library — Python 3.9.24 documentation
There is a backport of unittest.mock for earlier versions of Python, available as mock on PyPI.
Find elsewhere
🌐
Toptal
toptal.com › python › an-introduction-to-mocking-in-python
Python Mocking: A Guide to Better Unit Tests | Toptal®
May 19, 2026 - 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.
🌐
Python Tutorial
pythontutorial.net › home › python unit testing › python unittest mock
Python Unittest Mock
July 9, 2022 - from unittest.mock import MockCode language: Python (python)
🌐
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.
🌐
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())
🌐
Linode
linode.com › docs › guides › mock-testing-using-the-python-unittest-library
Mock Testing Using the Python Unittest Library | Linode Docs
December 3, 2021 - The Python unittest mock object library enables you to test areas of your application with mock objects and with assertions. One big advantage to using mock objects is that the testing code is located in one central location.
🌐
Safeguard
safeguard.sh › blog › devsecops › python unittest.mock: a practical guide with security in mind
Python unittest.mock Guide: Examples and Security Uses
April 23, 2026 - Python's unittest.mock is the standard-library tool for replacing real objects with controllable stand-ins during tests, and its most underrated use is security testing — it lets you exercise the error handling, permission checks, and failure ...
🌐
Testmuai
testmuai.com › testmu ai › blog › getting started with python unittest.mock library
Getting Started With Python unittest.mock Library
April 4, 2025 - Python's unittest.mock library, standard since 3.3, creates Mock and MagicMock objects and uses patch() to isolate code from dependencies during testing.
🌐
Reddit
reddit.com › r/learnpython › please explain unittest.mock
r/learnpython on Reddit: Please explain unittest.mock
January 9, 2019 -

There are several questions regarding this library that I need help understanding with.

  • What is the purpose of unittest.mock? How does it differ from unittest? Can one test just based on unittest without unittest.mock (or vice versa)?

  • What is a mock? Why are they used? Why are they important? What are the benefits of them versus just importing class objects from other user-defined modules to test?

  • How does the patch decorator work?

Please keep answers as rudimentary as possible.

Top answer
1 of 3
3
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.
2 of 3
1
What is meant by the `spec` parameter with `Mock`? When an object (or class) is passed what does that do? https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock spec: This can be either a list of strings or an existing object (a class or instance) that acts as the specification for the mock object. If I have a person class: class Person: def __init__(self, name, age): self.name = name self.age = age and do this below...what happens to Person in this case? mock_person = Mock(spec=Person)
🌐
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
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)
🌐
The Pi Guy
the-pi-guy.com › blog › mocking_with_unittestmock_in_python
Mocking with unittest.mock in Python
Unittest.mock is a powerful module in the Python standard library that allows you to isolate dependencies and test your code in isolation.
🌐
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 - unittest.mock provides a flexible way to create mock objects in Python. It allows you to replace parts of your system under test with mock…