Skip to main content
 首页 » 编程设计

python之模拟补丁一个类上不存在的函数

2025年05月04日10jyk

使用 Python 的 mock框架,是否可以模拟修补一个类中不存在的函数。如果是,怎么办?

例如:

example.py

import mock 
import unittest 
 
 
class MyClass(object): 
    pass 
 
 
class MyTests(unittest.TestCase): 
 
    def test_mock_non_existent_function(self): 
        with mock.patch('example.MyClass.my_function'): 
            pass 

运行该测试会引发错误:

Error 
Traceback (most recent call last): 
  File "/Users/jesse/Code/my_proj/lib/mock.py", line 1193, in patched 
  File "/Users/jesse/Code/my_proj/lib/mock.py", line 1268, in __enter__ 
  File "/Users/jesse/Code/my_proj/lib/mock.py", line 1242, in get_original 
AttributeError: <class 'example.MyClass'> does not have the attribute 'my_function' 

使用 Python 2.7.9 和 mock 1.0.1。

请您参考如下方法:

我相信这里的答案是使用 create 参数:

with mock.patch.object(MyClass, 'my_function', create=True) 

这在替换原始代码中的等效行时有效。