2017-07-27 152 views
0
def testedFunction(param): 
    try: 
     dic = OrderedDict(...) 
    except Exception: 
     ... 
def testedFunction(param): 
    try: 
     dic = OrderedDict(...) 
    except Exception: 
     ... 

我想單元測試異常,拋出給定的函數,所以爲了實現這一點,我試過使用unittest.mock.patch或unittest.mock.patch.object,無論失敗:Python,單元測試,模擬內置/擴展類的類方法

TypeError: can't set attributes of built-in/extension type 'collections.OrderedDict' 

我看了一些話題已經搜查像forbiddenfruit工具,但似乎都沒有給不工作。

我該如何模擬這種類的構造函數?

+0

可以請您發佈完整測試嗎? – dm03514

回答

1

這對我有效。它修補類OrderedDict用模擬物,並拋出異常,當對象的構造試圖調用模擬:

import collections 
from unittest.mock import patch 

def testedFunction(param): 
    try: 
     dic = collections.OrderedDict() 
    except Exception: 
     print("Exception!!!") 


with patch('collections.OrderedDict') as mock: 
    mock.side_effect = Exception() 
    testedFunction(1) 

時運行它顯示:

python mock_builtin.py 
Exception!!! 

Process finished with exit code 0 

對於「從收藏導入OrderedDict」語法,進口類必須嘲笑。因此,對於名爲mock_builtin.py的模塊,以下代碼給出了相同的結果:

from collections import OrderedDict 
from unittest.mock import patch 

def testedFunction(param): 
    try: 
     dic = OrderedDict() 
    except Exception: 
     print("Exception!!!") 


with patch('mock_builtin.OrderedDict') as mock: 
    mock.side_effect = Exception() 
    testedFunction(1) 
+0

使用tested_module.OrderedDict而不是collections.OrderedDict在補丁中做了竅門,謝謝:) – formateu