Skip to content Skip to sidebar Skip to footer

Can We Pass A Function And The Mocker To Another Function For Mocking?

I want to pass the function form along with the mocker to another function in the testing class, and expect the function will be mocked after returning. However, it seemed not work

Solution 1:

I might be mistaken, but it seems to me that what you're trying to do is called "Patching" in Python Mocker parlance. You want to change the behaviour of the submthd() call on the existing instance of Cls().

Firstly, you need to use new style classes (e.g. subclasses of object). So let's redefine Cls():

classCls(object):defsubmthd(self):
        return0defmthd(self):
        returnself.submthd()
    defsubmthd2(self):
        return0defmthd2(self):
        returnself.submthd()

I've added submthd2 and mthd2 to show how you can use your mockup(...) method on multiple methods, but otherwise your class is essentially unchanged.

Now, in order to use patching in your test case you would do something like this:

class Test_me(MockerTestCase):
    def mockup(self, p, f, m):
        methodToCall = getattr(p, f)
        methodToCall()
        m.result(1)

    def test_null(self):
        m = Mocker()
        o = Cls()
        p = m.patch(o)
        self.mockup(p, 'submthd', m)
        self.mockup(p, 'submthd2', m)
        m.replay()
        self.assertEqual(o.mthd(), 1)
        self.assertEqual(o.mthd2(), 1)
        m.verify()

When I run this code as a unit test I get:

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

OK

Post a Comment for "Can We Pass A Function And The Mocker To Another Function For Mocking?"