我try 过下面的代码,使用new_callable=PropertyMock来模拟属性调用,使用autospec=True来访问副作用函数中的self:
from unittest.mock import PropertyMock
def some_property_mock(self):
if self.__some_member == "some_value"
return "some_different_value"
else:
return "some_other_value"
mocker.patch.object(
SomeClass, "some_property", new_callable=PropertyMock, autospec=True, side_effect=some_property_mock)
它会引发以下异常: ValueError: Cannot use 'autospec' and 'new_callable' together
是否有其他替代方案来实现预期的行为?
编辑: 我try 过这篇文章https://stackoverflow.com/a/77940234/7217960中提供的解决方案,但它似乎不适用于PropertyMock.打印result会显示MyMock name='my_property()' id='136687332325264'而不是预期的2.
from unittest import mock
class MyClass(object):
def __int__(self):
self.my_attribute = 10
@property
def my_property(self):
return self.my_attribute + 1
def unit_under_test():
inst = MyClass()
return inst.my_property
class MyMock(mock.PropertyMock):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
print("MyMock __init__ called.")
with mock.patch.object(mock, 'MagicMock', MyMock):
with mock.patch.object(MyClass, 'my_property', autospec=True, side_effect=lambda self: 2) as spy:
result = unit_under_test()
assert result == 2
assert spy.call_count == 1