Skip to content Skip to sidebar Skip to footer

Why This Mocking Script Doesn't Work (unittest, Mocker, Python)

I want to mock MyClass.toBeMockedMethod which is called in MyClass.mymethod using the following script. It runs without actually mocking it. Not sure why.... class Test_mytest(Mock

Solution 1:

As with this question what you're really trying to do is patch your instance of MyClass. If MyClass is a new-style class then you can do this:

class Test_mytest(MockerTestCase):

    def mock_it_up(self, function, result = None, mmin = 0, mmax = None):
        methodToMock = getattr(self.p, function)
        methodToMock()
        self.m.result(result)
        self.m.count(mmin, mmax)

    def setUp(self):
        self.m = Mocker()
        self.o = MyClass(0)
        self.p = self.m.patch(self.o)
        self.mock_it_up('toBeMockedMethod')
        # Put more calls to mock_it_up here.
        self.m.replay()

    def test_one_atom(self):
        self.o.mymethod()

This will modify self.o so that calls to toBeMockedMethod are mocked.

However, if MyClass is not a new-style class then patching won't work. In this case, you can use type simulation to trick MyClass into doing what you want. For example:

class Test_mytest(MockerTestCase):

    def mock_it_up(self, function, result = None, mmin = 0, mmax = None):
        methodToMock = getattr(self.mockObj, function)
        methodToMock()
        self.m.result(result)
        self.m.count(mmin, mmax)

    def setUp(self):
        self.m = Mocker()
        self.o = MyClass(0)
        self.mockObj = self.m.mock(MyClass)
        self.mock_it_up('toBeMockedMethod')
        # Put more calls to mock_it_up here.
        self.m.replay()

    def test_one_atom(self):
        MyClass.mymethod(self.mockObj)

Note that the mocker's mock method is called with the class to be type-simulated. Later, instead of calling self.o.mymethod() we call MyClass.mymethod(...). Now MyClass.mymethod() expects an instance of MyClass as its first argument, but fortunately the mock object is masquerading as an instance of MyClass so the call goes through. When mymethod() calls toBeMockedMethod() it will actually call the mocked method, not the real method.

I quickly hacked up an test MyClass like this:

class MyClass():
    def __init__(self, x):
        self.x = x

    def toBeMockedMethod(self):
        print "Not Mocked!"

    def mymethod(self):
        self.toBeMockedMethod()

and when I ran this code as a unit test I got:

.
----------------------------------------------------------------------
Ran 1 test in 0.002s

OK

which is the desired result.


Post a Comment for "Why This Mocking Script Doesn't Work (unittest, Mocker, Python)"