2
使用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
。
而不是使用'patch'你可以只是做'example.MyClass.my_function =假()'。這確實意味着你沒有清理。 –
@ThomWiggers在做完這樣的猴子補丁後,我該如何去清理呢? –
恩,我想'del example.MyClass.my_function'應該可以工作... –