使用PythonUnitTest,如何确保类被实例化?
鉴于以下情况:使用PythonUnitTest,如何确保类被实例化?,python,unit-testing,mocking,Python,Unit Testing,Mocking,鉴于以下情况: 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):
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
def testCreated(self):
created = MagicMock(spec=toCreate)
toTest.createObject()
created.__init__.assert_called_once_with()
…我如何确保toCreate
实际上已创建?我尝试了以下方法:
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
def testCreated(self):
created = MagicMock(spec=toCreate)
toTest.createObject()
created.__init__.assert_called_once_with()
但是我得到了以下错误:AttributeError:Mock对象没有属性“init”
。我是否误用了MagicMock类,如果是,如何误用?有两个主要职责:
- 定义
对象:设计用于跟随您的剧本并记录对模拟对象的每次访问的对象Mock
- 修补引用并恢复原始状态
以创建类引用,在这里您可以拥有完整的行为控制。有很多方法可以使用,一些和
在您的情况下,您应该patch
来创建类实例,并检查是否调用用于替换构造函数的patch
的Mock
:
class TestThing(unittest.TestCase):
@patch("module_where_toCreate_is.toCreate")
def testCreated(self, mock_toCreate):
creator = toTest()
toTest.createObject()
mock_toCreate.assert_called_with()