How to patch an entire class in a unit test

  mocking, python, unit-testing

In unit tests, I’m used to writing

def patched_function():

@patch("package.module.function", new=patched_function)
class TestExample:

And then any time the code I’m testing calls package.module.function, it instead called patched function. But what if I want to patch an entire class? I know about Mock, but that won’t work because it’s the code I’m testing that’s instantiating the class. I don’t have control of it. I would think I could do this:

def PatchedClass():
    def __init__(self):
        # patched constructor

    def method(self):
        # patched method

@patch("package.module.Class", new=PatchedClass)
class TestExample:

I would think this would replace all calls to instantiate the given class with my patched class. But it doesn’t seem to do anything. How can I patch out the whole class?

Source: Python Questions