Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用PythonUnitTest,如何确保类被实例化?_Python_Unit Testing_Mocking - Fatal编程技术网

使用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()