How to mock out a function that's returned from getattr?

2.8k views Asked by At

I have a class that does something like:

class MyClass(object):
    def __init__(self, delegate_to):
        self._delegate_to = delegate_to

    def __getattr__(self, item):
        return getattr(self._delegate_to, item)

But when I try to do something like:

my_mock = self.mox.CreateMock(MyClass)
my_mock.f().AndReturn(None)

mox errors with:

UnknownMethodCallError: Method called is not a member of the object: f

How do I mock out the delegated calls?

1

There are 1 answers

0
Noel Yap On BEST ANSWER

Hacky, but try:

class MyMock(MyClass):
    def f():
        pass

then in the test:

my_mock = self.mox.CreateMock(MyMock)
my_mock.f().AndReturn(None)