如何模拟从getattr返回的函数?

时间:2012-06-04 18:32:15

标签: python mox

我有一个类似于:

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

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

但是当我尝试做类似的事情时:

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

mox错误:

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

如何模拟委派的电话?

1 个答案:

答案 0 :(得分:2)

Hacky,但请尝试:

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

然后在测试中:

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