2017-03-08 63 views
1

我需要測試我的類的構造函數調用一些方法測試構造使用模擬

class ProductionClass: 
    def __init__(self): 
     self.something(1, 2, 3) 

    def method(self): 
     self.something(1, 2, 3) 

    def something(self, a, b, c): 
     pass 

這個類是從「unittest.mock - 入門」。正如在那裏寫的,我可以確保'方法'如下所示。

real = ProductionClass() 
real.something = MagicMock() 
real.method() 
real.something.assert_called_once_with(1, 2, 3) 

但如何測試相同的構造函數?

回答

2

您可以使用補丁(查看文檔https://docs.python.org/dev/library/unittest.mock.html)並聲明在創建對象的新實例後,something方法被調用一次並用所需的參數調用。例如,在你的例子中,它會是這樣的:

from unittest.mock import MagicMock, patch 
from your_module import ProductionClass 

@patch('your_module.ProductionClass.something') 
def test_constructor(something_mock): 
    real = ProductionClass() 
    assert something_mock.call_count == 1 
    assert something_mock.called_with(1,2,3)