Python Unitest模拟一个对象没有属性
如果对象具有某个属性,则我的函数可以运行一些代码,在极少数情况下,如果对象没有属性,则运行不同的代码。我很难在没有测试属性的情况下创建对象。我尝试了del instance.attribute
,但出现了错误。该属性实际上是引擎盖下方的@property
。
我有一个具有foo
属性的对象实例
。一个人如何模拟它,以便当一个人尝试访问instance.foo
时,如果没有属性,它会像往常一样添加attributeError
?
我尝试了mock.mock(side_effect = attributeError('boom!'))
,但它仅适用于方法。
I have a function that runs some code if the object has a certain attribute, and in rare cases if if the object does not have the attribute, it runs different code. It is hard for me to create the object without the attribute for testing. I tried del instance.attribute
but got an error. The attribute is actually a @property
under the hood.
I have an object instance
that has foo
attribute. How does one mock it so that when one tries to access instance.foo
it raises an AttributeError
as usual if there is no attribute?
I tried mock.Mock(side_effect=AttributeError('Boom!'))
but it only works with methods.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以尝试使用属性,通常您可以设置各自的副作用。这是一个简单的工作示例:
当您修补类中的属性而不是对象中的属性时,您也可以使用
patch.Object
进行此操作,如果您可以通过访问对象访问对象的访问对象:You could try to use a PropertyMock for the property, and generally you shall be able to set the respective side effect. Here is a simple working example:
As you patch the property in the class, not in the object, you can can also do this using
patch.object
if you have access to the object by accessing the class of the object: