我正在尝试模拟我正在测试的函数中使用的函数,但由于某种原因,我没有看到原始函数始终运行,而不是我创建为模拟的函数。
我正在测试的代码具有这种类型的设置:
def function_being_tested(foo):
...
function_i_want_to_mock(bar)
...
def function_i_want_to_mock(bar)
print("Inside original function")
...
我已经安装了Mock并且尝试使用unittest.mock补丁
当前测试文件使用此设置:
import mock
from django.test import TestCase
def mock_function_i_want_to_mock(bar):
print(bar)
return True
class SupportFunctionsTestCases(TestCase):
@mock.patch("path.to.function.function_i_want_to_mock", mock_function_i_want_to_mock)
def test_function_being_tested(self):
# setup
result = function_being_tested(test_foo)
self.assertEqual(result, expected_result)
然后发生的事情是,当我运行测试时,我总是得到:“在原始函数内”,而不是打印的参数,因此它始终运行原始函数。
我之前使用过这个确切的设置并且它有效,所以我不确定是什么原因造成的。可能是一些错误的设置...
如果有人有不同的方法来做到这一点或发现一些错误,我们将不胜感激。
"path.to.function.function_i_want_to_mock"
应该是使用该函数的路径,而不是定义的路径。
因此,如果
function_i_want_to_mock
在 module_A.py
中定义,但在您正在测试的 module_B.py
中导入并使用,那么您应该使用 @mock.patch("path.to.module_B.function_i_want_to_mock", ...)
。