Search code examples
pythonunit-testinginheritancemocking

Python mock: mocking base class for inheritance


I am testing a class that inherits from another one very complex, with DB connection methods and a mess of dependences. I would like to mock its base class so that I can nicely play with the method defined in the subclass, but in the moment I inherit from a mocked class, the object itself turns a mock and loses all its methods.

How can I mock a superclass?

More or less the situation can be summed up in this:

import mock

ClassMock = mock.MagicMock()

class RealClass(ClassMock):

    def lol(self):
        print 'lol'

real = RealClass()
real.lol()  # Does not print lol, but returns another mock

print real # prints <MagicMock id='...'>

This is a simplified case. What is actually happening is that RealClass extends AnotherClass, but I managed to intercept the AnotherClass and replace it with a mock.


Solution

  • This should work for you.

    import mock
    
    ClassMock = mock.MagicMock # <-- Note the removed brackets '()'
    
    class RealClass(ClassMock):
    
        def lol(self):
            print 'lol'
    
    real = RealClass()
    real.lol()  # Does not print lol, but returns another mock
    
    print real # prints <MagicMock id='...'>
    

    You should'nt pass an instance of the class as you did. mock.MagicMock is a class, so you pass it directly.

    In [2]: inspect.isclass(mock.MagicMock)
    Out[2]: True