模拟 class 属性

Mocking a class attribute

我有一个 class,我想模拟一个 class 属性

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()

我还尝试了直接赋值以及此 post 中的其他建议: 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