【发布时间】:2015-11-15 15:18:30
【问题描述】:
使用 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。
【问题讨论】:
-
你可以使用
example.MyClass.my_function = Mock(),而不是使用patch。这确实意味着您没有进行清理。 -
@ThomWiggers 在做了这样的猴子补丁后,我该如何清理?
-
呃,我猜
del example.MyClass.my_function应该可以工作...
标签: python python-2.7 unit-testing mocking