mock a subset of a python class’s methods and properties

Instead of patching the whole class, you must patch the object. Namely, make an instance of your class, then, patch the methods of that instance.

Note that you can also use the decorator @patch.object instead of my approach.

class SomeClass:
    def some_method(self):
        return 100

    def another_method(self):
        return 500

In your

from unittest import mock

class Tests(unittest.TestCase):

    def test_some_operation(self):
        some_class_instance = SomeClass()

        # I'm mocking only the some_method method.
        with mock.patch.object(some_class_instance, 'some_method', return_value=25) as cm:

            # This is gonna be ok

            # The other methods work as they were supposed to.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top