使用Python unittest,我如何确保实例化一个Class?

时间:2016-01-12 15:20:26

标签: 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):
        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类,如果是这样的话?

1 个答案:

答案 0 :(得分:0)

unitetest.mock有两个主要职责:

  • 定义Mock个对象:旨在关注您的剧本并记录对您模拟对象的每次访问的对象
  • 修补引用并恢复原始状态

在您的示例中,您需要两个功能:通过模拟修补toCreate类引用,您可以在其中进行完整的行为控制。有很多方法可以使用patch,有些details to take care on how use itcavelets 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()
相关问题