我有一个要模拟的具有单个类属性的类
my_class.py
class MyClass:
__attribute = ['123', '456']
test_my_class.py
import pytest
from directory.my_class import MyClass
def test_1(mocker):
with mocker.patch.object(MyClass, '__attribute', {'something': 'new'}):
test = MyClass()
我得到:
E AttributeError: <class 'directory.my_class.MyClass'> does not have the attribute '__attribute'
尝试时我也遇到同样的错误:
def test_2(mocker):
with mocker.patch('directory.my_class.MyClass.__attribute', new_callable=mocker.PropertyMock) as a:
a.return_value = {'something': 'new'}
test = MyClass()
我还尝试了直接赋值以及本文中的其他建议:Better way to mock class attribute in python unit test
我的项目正在使用此插件中的模拟装置:https : //pypi.org/project/pytest-mock/
你可以用一个 PropertyMock
from unittest.mock import patch, PropertyMock
class MyClass:
attr = [1, 2, 3]
with patch.object(MyClass, "attr", new_callable=PropertyMock) as attr_mock:
attr_mock.return_value = [4, 5, 6]
print(MyClass.attr) # prints [4, 5, 6]
print(MyClass.attr) # prints [1, 2, 3]
文档参考:https : //docs.python.org/3/library/unittest.mock.html#unittest.mock.PropertyMock
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句