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

时间:2017-07-27 16:19:50

标签: python unit-testing mocking python-3.5

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'

我已经阅读了一些主题并搜索了像forbiddenfruit这样的工具,但这似乎根本不起作用。

我如何模拟那种类的构造函数?

1 个答案:

答案 0 :(得分:1)

这对我有用。当对象构造尝试调用mock时,它会使用mock修补类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

对于'from collections import 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)