属性错误:扩展 MagicMock 类时_mock_methods



是否可以扩展 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)

相关内容

  • 没有找到相关文章

最新更新