如何使用Mox模拟类属性? [英] How do I mock a class property with mox?

查看:94
本文介绍了如何使用Mox模拟类属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堂课

class MyClass(object):
    @property
    def myproperty(self):
        return 'hello'

使用> mox py.test,如何模拟出?

Using mox and py.test, how do I mock out myproperty?

我尝试过:

mock.StubOutWithMock(myclass, 'myproperty')
myclass.myproperty = 'goodbye'

mock.StubOutWithMock(myclass, 'myproperty')
myclass.myproperty.AndReturns('goodbye')

,但都失败,并显示AttributeError: can't set attribute.

推荐答案

对类属性进行存根时,mox使用setattr.因此

When stubbing out class attributes mox uses setattr. Thus

mock.StubOutWithMock(myinstance, 'myproperty')
myinstance.myproperty = 'goodbye'

等同于

# Save old attribute so it can be replaced during teardown
saved = getattr(myinstance, 'myproperty')
# Replace the existing attribute with a mock
mocked = MockAnything()
setattr(myinstance, 'myproperty', mocked)

请注意,由于myproperty是属性getattrsetattr将调用该属性的__get____set__方法,而不是实际模拟"该属性本身.

Note that because myproperty is a property getattr and setattr will be invoking the property's __get__ and __set__ methods, rather than actually "mocking out" the property itself.

要获得所需的结果,您只需要再深入一步并在实例的类上模拟该属性即可.

Thus to get your desired outcome you just go one step deeper and mock out the property on the instance's class.

mock.StubOutWithMock(myinstance.__class__, 'myproperty')
myinstance.myproperty = 'goodbye'

请注意,如果您希望同时模拟具有不同myproperty值的MyClass的多个实例,这可能会导致问题.

Note that this might cause issues if you wish to concurrently mock multiple instances of MyClass with different myproperty values.

这篇关于如何使用Mox模拟类属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆