我有一门课:
class MyClass(object):
@property
def myproperty(self):
return 'hello'如何使用mox和py.test模拟myproperty
我试过了:
mock.StubOutWithMock(myclass, 'myproperty')
myclass.myproperty = 'goodbye'和
mock.StubOutWithMock(myclass, 'myproperty')
myclass.myproperty.AndReturns('goodbye')但使用AttributeError: can't set attribute时,这两种方法都失败了。
发布于 2010-03-26 06:06:43
在清除类属性时,mox使用setattr。因此
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__方法,而不是实际“模拟”该属性本身。
因此,要获得您想要的结果,只需更深入一步,模拟实例类上的属性即可。
mock.StubOutWithMock(myinstance.__class__, 'myproperty')
myinstance.myproperty = 'goodbye'请注意,如果您希望同时模拟具有不同myproperty值的多个MyClass实例,这可能会导致问题。
发布于 2010-03-25 18:18:00
你读过关于property的书吗?它是只读的,是一个"getter“。
如果你想要一个setter,你有两个选择来创建它。
一旦你同时拥有了getter和setter,你可以再次尝试模拟它们。
class MyClass(object): # Upper Case Names for Classes.
@property
def myproperty(self):
return 'hello'
@myproperty.setter
def myproperty(self,value):
self.someValue= value或
class MyClass(object): # Upper Case Names for Classes.
def getProperty(self):
return 'hello'
def setProperty(self,value):
self.someValue= value
myproperty= property( getProperty, setProperty )https://stackoverflow.com/questions/2512453
复制相似问题