鉴于以下内容:
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
...我怎样才能确保toCreate
实际上已经创建了?我尝试过以下方法:
def testCreated(self):
created = MagicMock(spec=toCreate)
toTest.createObject()
created.__init__.assert_called_once_with()
但是我收到以下错误:AttributeError: Mock object has no attribute 'init'
。我是否滥用了MagicMock类,如果是这样的话?
答案 0 :(得分:0)
unitetest.mock
有两个主要职责:
Mock
个对象:旨在关注您的剧本并记录对您模拟对象的每次访问的对象在您的示例中,您需要两个功能:通过模拟修补toCreate
类引用,您可以在其中进行完整的行为控制。有很多方法可以使用patch
,有些details to take care on how use it和cavelets to know。
在您的情况下,您应该patch
toCreate
类实例并检查您是否调用Mock
patch
用于替换构造函数:
class TestThing(unittest.TestCase):
@patch("module_where_toCreate_is.toCreate")
def testCreated(self, mock_toCreate):
creator = toTest()
toTest.createObject()
mock_toCreate.assert_called_with()