如何用模拟模拟只读属性? [英] How to mock a readonly property with mock?
问题描述
如何使用 mock 模拟只读属性?
How do you mock a readonly property with mock?
我尝试过:
setattr(obj.__class__, 'property_to_be_mocked', mock.Mock())
但是问题在于它随后适用于该类的所有实例...这破坏了我的测试.
but the issue is that it then applies to all instances of the class... which breaks my tests.
您还有其他想法吗?我不想模拟整个对象,仅模拟这个特定属性.
Do you have any other idea? I don't want to mock the full object, only this specific property.
推荐答案
我认为更好的方法是将属性模拟为PropertyMock
,而不是直接模拟__get__
方法.
I think the better way is to mock the property as PropertyMock
, rather than to mock the __get__
method directly.
在文档中进行了说明,搜索unittest.mock.PropertyMock
:
拟用作类的属性或其他描述符的模拟. PropertyMock
提供了__get__
和__set__
方法,因此您可以在获取返回值时指定其返回值.
It is stated in the documentation, search for unittest.mock.PropertyMock
:
A mock intended to be used as a property, or other descriptor, on a class. PropertyMock
provides __get__
and __set__
methods so you can specify a return value when it is fetched.
方法如下:
class MyClass:
@property
def last_transaction(self):
# an expensive and complicated DB query here
pass
def test(unittest.TestCase):
with mock.patch('MyClass.last_transaction', new_callable=PropertyMock) as mock_last_transaction:
mock_last_transaction.return_value = Transaction()
myclass = MyClass()
print myclass.last_transaction
mock_last_transaction.assert_called_once_with()
这篇关于如何用模拟模拟只读属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!