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
mox
usessetattr
. Thusis equivalent to
Note that because
myproperty
is a propertygetattr
andsetattr
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.
Note that this might cause issues if you wish to concurrently mock multiple instances of MyClass with different
myproperty
values.