I have a class:
class MyClass(object):
@property
def myproperty(self):
return 'hello'
Using mox and py.test, how do I mock out myproperty?
I've tried:
mock.StubOutWithMock(myclass, 'myproperty')
myclass.myproperty = 'goodbye'
and
mock.StubOutWithMock(myclass, 'myproperty')
myclass.myproperty.AndReturns('goodbye')
but both fail with AttributeError: can't set attribute.
When stubbing out class attributes
moxusessetattr. Thusis equivalent to
Note that because
mypropertyis a propertygetattrandsetattrwill 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.
Note that this might cause issues if you wish to concurrently mock multiple instances of MyClass with different
mypropertyvalues.