扩展 MagicMock 类时出现 AttributeError: _mock_methods

ale*_*ria 6 python python-unittest magicmock

是否可以扩展 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)
Run Code Online (Sandbox Code Playgroud)

但这会引发以下错误:

  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
Run Code Online (Sandbox Code Playgroud)

ale*_*ria 5

通过添加修复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)
Run Code Online (Sandbox Code Playgroud)