2016-01-12 37 views
0

考慮以下幾點:使用Python unittest,我如何確保一個類被實例化?

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

unitetest.mock有兩個主要任務:

  • 定義Mock對象:對象設計遵循你的劇本和每次訪問記錄到你的嘲笑對象
  • 修補參考,並恢復原來的狀態

在你的例子中,你需要兩個功能:通過模擬修補toCreate類引用,你可以擁有一個完整的行爲控制。有很多方法可以使用patch,一些details to take care on how use itcavelets to know

在你的情況,你應該如果調用Mockpatch用於替換的構造patchtoCreate類的實例,並檢查:

class TestThing(unittest.TestCase): 
    @patch("module_where_toCreate_is.toCreate") 
    def testCreated(self, mock_toCreate): 
     creator = toTest() 
     toTest.createObject() 
     mock_toCreate.assert_called_with() 
相關問題