Here's a quick'n'dirty example to get you going:

import mock
import unittest

class ClassToPatch():
   def __init__(self, *args):
       pass

   def some_func(self):
       return id(self)

class UUT():
    def __init__(self, *args):
        resource_1 = ClassToPatch()
        resource_2 = ClassToPatch()
        self.test_property = (resource_1.some_func(), resource_2.some_func())

class TestCase1(unittest.TestCase):
    @mock.patch('__main__.ClassToPatch', autospec = True)
    def test_1(self, mock1):
        ctpMocks = [mock.Mock(), mock.Mock()]
        ctpMocks[0].some_func.return_value = "funky"
        ctpMocks[1].some_func.return_value = "monkey"
        mock1.side_effect = ctpMocks

        u = UUT()
        self.assertEqual(u.test_property, ("funky", "monkey"))

if __name__ == '__main__':
    unittest.main()

I've added test_property to UUT so that the unit test does something useful. Now, without the mock test_property should be a tuple containing the ids of the two ClassToPatch instances. But with the mock it should be the tuple: ("funky", "monkey").

I've used the side_effect property of the mock object so that a different instance of ClassToPatch is returned on each call in the UUT initialiser.

Hope this helps.

Edit: Oh, by the way, when I run the unit test I get:

.
----------------------------------------------------------------------
Ran 1 test in 0.004s

OK
Answer from srgerg on Stack Overflow
Top answer
1 of 2
39

Here's a quick'n'dirty example to get you going:

import mock
import unittest

class ClassToPatch():
   def __init__(self, *args):
       pass

   def some_func(self):
       return id(self)

class UUT():
    def __init__(self, *args):
        resource_1 = ClassToPatch()
        resource_2 = ClassToPatch()
        self.test_property = (resource_1.some_func(), resource_2.some_func())

class TestCase1(unittest.TestCase):
    @mock.patch('__main__.ClassToPatch', autospec = True)
    def test_1(self, mock1):
        ctpMocks = [mock.Mock(), mock.Mock()]
        ctpMocks[0].some_func.return_value = "funky"
        ctpMocks[1].some_func.return_value = "monkey"
        mock1.side_effect = ctpMocks

        u = UUT()
        self.assertEqual(u.test_property, ("funky", "monkey"))

if __name__ == '__main__':
    unittest.main()

I've added test_property to UUT so that the unit test does something useful. Now, without the mock test_property should be a tuple containing the ids of the two ClassToPatch instances. But with the mock it should be the tuple: ("funky", "monkey").

I've used the side_effect property of the mock object so that a different instance of ClassToPatch is returned on each call in the UUT initialiser.

Hope this helps.

Edit: Oh, by the way, when I run the unit test I get:

.
----------------------------------------------------------------------
Ran 1 test in 0.004s

OK
2 of 2
3

Here is another version which is more generic to handle any number of instances created:

class TestUUT:
    def test_init(self, mocker):
        class MockedClassToPatchMeta(type):
            static_instance = mocker.MagicMock(spec=ClassToPatch)

            def __getattr__(cls, key):
                return MockedClassToPatchMeta.static_instance.__getattr__(key)

        class MockedClassToPatch(metaclass=MockedClassToPatchMeta):
            original_cls = ClassToPatch
            instances = []

            def __new__(cls, *args, **kwargs):
                MockedClassToPatch.instances.append(
                    mocker.MagicMock(spec=MockedClassToPatch.original_cls))
                MockedClassToPatch.instances[-1].__class__ = MockedClassToPatch
                return MockedClassToPatch.instances[-1]

        mocker.patch(__name__ + '.ClassToPatch', new=MockedClassToPatch)

        UUT()

        # since your original code created two instances
        assert 2 == len(MockedClassToPatch.instances)

If you need more thorough validation for each instance you can access MockedClassToPatch.instances[0] or MockedClassToPatch.instances[1].

I've also created a helper library to generate the meta class boilerplate for me. To generate the needed code for your example I wrote:

print(PytestMocker(mocked=ClassToPatch, name=__name__).mock_classes().mock_classes_static().generate())
🌐
Medium
medium.com › @hema-chandra › mocking-patching-class-instance-variables-in-python-testing-31d1e7447544
Mocking/Patching Class & Instance variables in Python Testing | by Hemachandra | Medium
August 31, 2023 - This article provides an overview of how to use the unittest module to mock or patch class and instance variables within a Python class. By…
🌐
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. See the quick guide for some examples of how to use Mock, MagicMock and patch(). Mock is designed for use with unittest and is based on the ‘action -> assertion’ pattern instead of ‘record -> replay’ used by many mocking frameworks. There is a backport of unittest.mock for earlier versions of Python, available as mock on PyPI.
🌐
Kimsereylam
kimsereylam.com › python › 2021 › 03 › 19 › how-to-use-patch-in-python-unittest.html
How To Use Patch In Python Unittest
March 19, 2021 - Starting from the instance attribute being used in get_value, we can patch it by patching my_class.MyClass.
🌐
Python
docs.python.org › 3 › library › unittest.mock-examples.html
unittest.mock — getting started
This can feel like unnecessary repetition. Instead, you can use patch() (in all its various forms) as a class decorator. This applies the patches to all test methods on the class.
🌐
Python Tutorial
pythontutorial.net › home › python unit testing › python patch()
Python patch() - Replace a Target with a Mock Object
July 9, 2022 - When you use the patch() as a decorator of a function or class, inside the function or class the target is replaced with a new object.
🌐
Real Python
realpython.com › python-mock-library
Understanding the Python Mock Object Library – Real Python
May 29, 2026 - Mock, along with its subclasses, ... The library also provides a function called patch(), which replaces the real objects in your code with Mock instances....
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 - 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.
🌐
GitHub
gist.github.com › blaix › 4150999
Patching an entire test class in python · GitHub
Patching an entire test class in python. GitHub Gist: instantly share code, notes, and snippets.
🌐
Paulbutcher
paulbutcher.space › blog › 2021 › 06 › 17 › patching-methods-in-python
Patching Methods in Python | Paul’s Blog
June 17, 2021 - from unittest import mock class MyClass: def __init__(self): print('hello') self.my_property = 'dolly' def do_something(self): print('world') def do_something_else(self): print(self.my_property) def do_yet_another_thing(self): o = MyOtherClass() print(f"{o.do_something()} {self.do_something()}") class MyOtherClass: def do_something(self): return 'goodbye' print('exercise the class normally:') o = MyClass() o.do_something() o.do_something_else() o.do_yet_another_thing() print('\nexercise the patched class:') with mock.patch.object(MyClass, '__init__', return_value=None): # Note that it does not say "hello" at this point o2 = MyClass() # Here, it prints "world" o2.do_something() # If the real function you are exercising relies on # properties set in __init__, you will have to # set them here instead.
🌐
Linux find Examples
queirozf.com › entries › python-unittest-examples-mocking-and-patching
Python Unittest Examples: Mocking and Patching
November 26, 2022 - Use patch.object(MyClass, 'my_method', return_value="return value"): ... class MyClass: def __init__(self, name): self.name = name def sayhi(self): return "hi my name is: {}".format(self.name) # instantiates MyClass and calls a method on the object def function_b(): param1 = MyClass("foo") # returns "hi my name is: foo" return param1.sayhi()
🌐
Python.org
discuss.python.org › python help
How to mock all the methods of one class - Python - Python Help - Discussions on Python.org
March 1, 2021 - Hi Everyone, I am trying to mock an entire class using patch. Imagine that class isMyClass() with methods foo() and bar() both of which return a boolean. The way I was attempting it was by including fixture in the conftest.py for example @pytest.fixture(scope="session") def mock_myclass() -> MagicMock: with patch("module.file.MyClass") as myclass_mocked: myclass_mocked.foo.return_value = True myclass_mocked.bar.return_value = True yield myclass_mocked Then I h...
🌐
Trey Hunner
treyhunner.com › 2014 › 10 › the-many-flavors-of-mock-dot-patch
The many flavors of mock.patch
October 14, 2014 - I frequently use the patch function from Michael Foord’s mock library (now available in Python 3.4 as unittest.mock) to monkey patch my code. While chatting with other users of patch, I realized that everyone seems to have their own favorite way to use it. In this post I will discuss the ways I use patch. ... from mock import patch class MyModelTest: @patch('mylib.utils.other_func') def test_some_func(self, other_func): other_func.return_value = "MY STRING" assert some_func("my string") == "MY STRING" other_func.assert_called_once_with("my string")
🌐
DEV Community
dev.to › chen_ashkenazi › mocking-python-classes-4h96
Mocking Python Classes - DEV Community
August 27, 2024 - @pytest.fixture def class_a_mock(mock_class_b, mock_class_c): with patch.object(target=ClassA, attribute="__init__", return_value=None) as mock_init: class_a = ClassA() class_a.class_b = mock_class_b class_a.class_c = mock_class_c class_b.count = 0 return class_a · The important part is how to use the patch.object function, which is from unittest.mock module in Python.
🌐
Chase Seibert Blog
chase-seibert.github.io › blog › 2015 › 06 › 25 › python-mocking-cookbook.html
Python Mock Cookbook - Chase Seibert Blog
June 25, 2015 - What about a @classmethod on a class? It’s the same as a method. @mock.patch('myapp.app.Car.for_make') def test_classmethod(self, mock_for_make): new_car = Car() new_car.make = 'Chevy' mock_for_make.return_value = new_car ...
🌐
GitHub
github.com › python › cpython › issues › 93582
mock.patch applied at class level behaves incorrectly · Issue #93582 · python/cpython
June 7, 2022 - # a.py import unittest from unittest import mock def f(): return 41 def g(): return 43 class BaseFTests(unittest.TestCase): def test_a(self): self._asserts(f()) def _asserts(self, val): print(self, val) @mock.patch('a.f', new=lambda: 2) class MockedFTests(BaseFTests): def _asserts(self, val): print(self, val) self.assertEqual(val, 2) self.assertEqual(g(), 43) @mock.patch('a.g', new=lambda: 3) class MockedFMockedGTests(MockedFTests): def _asserts(self, val): print(self, val) self.assertEqual(val, g()-1) class MockedFStraightGTests(MockedFTests): def _asserts(self, val): print(self, val) self.as
Author: python
🌐
CodeRivers
coderivers.org › blog › python-patch
Python Patch: An In - Depth Exploration - CodeRivers
February 22, 2026 - Python patch involves modifying the behavior of a piece of code (function, method, or class) during a specific period, usually for testing or dynamic code adaptation.
🌐
Toptal
toptal.com › python › an-introduction-to-mocking-in-python
Python Mocking: A Guide to Better Unit Tests | Toptal®
May 19, 2026 - class Target: def apply(self, value, are_you_sure): if are_you_sure: return value else: return None · Re-run your test, and you’ll find that it still passes. That’s because it isn’t built against your actual API. This is why you should always use the create_autospec method and the autospec parameter with the @patch and @patch.object decorators. To finish up, let’s write a more applicable real-world Python ...
🌐
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 decorator is applied to my_module.MyClass.some_method, which means it attempts to replace the class method directly.
🌐
Medium
medium.com › uckey › how-mock-patch-decorator-works-in-python-37acd8b78ae
How mock.patch decorator works in python | by Yuki Nishiwaki | ukinau | Medium
February 24, 2018 - Basically this function will generate the decorator function with “getter” which is the function to return actual object having attribute you wanted to replace and “attribute” which is the name of the object you want to replace. and then generate “_patch class” object which will be decorator with these. Since probably explaining by only text is not easy thing so let me write python code do same thing as first example.