如何使用Mox模拟类属性? [英] How do I mock a class property with 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
是属性getattr
和setattr
将调用该属性的__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屋!