5

Is it okay to extend a MagicMock class to create mocked objects and use it in unit tests?

If i don't have any code in init function the extending the class seems to work well

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)

but this throws the following error:

  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
alegria
  • 1,290
  • 14
  • 23

1 Answers1

4

Fixed by adding 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)
andy boot
  • 11,355
  • 3
  • 53
  • 66
alegria
  • 1,290
  • 14
  • 23