Reputation: 1002
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?
Upvotes: 1
Views: 1473
Reputation: 23711
unitetest.mock
have two main duties:
Mock
objects: objects that are designed to follow your screenplay and record every access to your mocked objectIn 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()
Upvotes: 1