[英]Python, unit test, mock built-in/extension type class method
def testedFunction(param):
try:
dic = OrderedDict(...)
except Exception:
...
我想对给定函数内的异常进行单元测试,因此为了实现此目的,我尝试使用unittest.mock.patch或unittest.mock.patch.object,但均失败:
TypeError: can't set attributes of built-in/extension type 'collections.OrderedDict'
我已经阅读了一些主题,并在搜索诸如禁止水果之类的工具,但这似乎根本不起作用。
如何模拟此类的构造函数?
这对我有用。 它使用模拟补丁修补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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.