gpt4 book ai didi

python - 属性错误 : _mock_methods when extending MagicMock class

转载 作者:行者123 更新时间:2023-12-04 15:24:33 26 4
gpt4 key购买 nike

是否可以扩展 MagicMock 类来创建模拟对象并在单元测试中使用它?
如果我在 init 函数中没有任何代码,则扩展类似乎运行良好

class MockAPI(MagicMock):

def __init__(self):
self.x = 20

def mocked_method(self, param):
return not param


class TestX(TestCase):
def setUp(self) -> None:
self.mocked_api = MockAPI()

def test_another_method(self):
self.assertTrue(True)
但这会引发以下错误:
  File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/case.py", line 59, in testPartExecutor
yield
File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/case.py", line 611, in run
self.setUp()
File "/Users/user/project/tests/test_protocols.py", line 46, in setUp
self.mocked_api = MockAPI()
File "/Users/user/project/tests/test_protocols.py", line 38, in __init__
self.x = 20
File "/Users/user/project/venv/lib/python3.7/site-packages/mock/mock.py", line 736, in __setattr__
elif (self._spec_set and self._mock_methods is not None and
File "/Users/user/project/venv/lib/python3.7/site-packages/mock/mock.py", line 630, in __getattr__
elif self._mock_methods is not None:
File "/Users/user/project/venv/lib/python3.7/site-packages/mock/mock.py", line 629, in __getattr__
raise AttributeError(name)
AttributeError: _mock_methods

最佳答案

通过添加 super().__init__(): 修复

class MockAPI(MagicMock):
def __init__(self):
super().__init__()
self.x = 20

def mocked_method(self, param):
return not param



class TestX(TestCase):
def setUp(self) -> None:
self.mocked_api = MockAPI()

def test_another_method(self):
self.assertTrue(True)

关于python - 属性错误 : _mock_methods when extending MagicMock class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62542234/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com