Python,单元测试,模拟内置/扩展类的类方法

问题描述:

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

这对我有效。它修补类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