【发布时间】:2015-11-09 23:01:34
【问题描述】:
我注意到类方法已被正确模拟出来,但该函数绕过模拟并运行实际函数。
from module1 import myClass
from module2 import my_function
import unittest
from mock import patch
class TestStuff(unittest.TestCase):
@patch('module2.my_function')
@patch('module1.myClass.my_method')
def test_my_function(self, mock_method, mock_function):
test_obj = myClass()
test_obj.my_method()
assert mock_method.called
my_function()
assert mock_function.called
如果我打印出 my_function() 和 type(my_function) 它不会显示模拟,而是真正的功能。我导入一个类然后模拟一个方法是否重要,但我直接导入函数?
【问题讨论】:
-
my_function长什么样子? -
我的函数查询数据库并返回对象列表。我想模拟它以避免读取/写入数据库。类方法对第三方进行 API 调用,所以我也想模拟一下。
标签: python unit-testing mocking patch