1

Given the following:

class toTest(object)
    def createObject(self):
        self.created = toCreate()

class toCreate(object):
    def __init__(self):
        pass

# testFile.py
import unittest
class TestThing(unittest.TestCase):
    def testCreated(self):
        creator = toTest()
        toTest.createObject()
        # -- Assert that the 'toCreate' object was in fact instantiated

...how can I ensure that toCreate was in fact created? I have tried the following:

def testCreated(self):
    created = MagicMock(spec=toCreate)
    toTest.createObject()
    created.__init__.assert_called_once_with()

But I get the following error: AttributeError: Mock object has no attribute 'init'. Am I misusing the MagicMock class, and if so how?

1 Answer 1

1

unitetest.mock have two main duties:

  • Define Mock objects: objects that are designed to follow your screenplay and record every access to your mocked object
  • Patch references and recover the original state

In your example you need both functionalities: Patching toCreate a class reference by a mock where you can have complete behavior control. There are a lot of ways to use patch, some details to take care on how use it and caveats to know.

In your case you should patch toCreate a class instance and check if you call the Mock that patch used to replace the constructor:

class TestThing(unittest.TestCase):
    @patch("module_where_toCreate_is.toCreate")
    def testCreated(self, mock_toCreate):
        creator = toTest()
        toTest.createObject()
        mock_toCreate.assert_called_with()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.