无法在 Python (Django) 中模拟函数

ste*_*rey 6 python django unit-testing python-3.x

我正在尝试模拟我正在测试的函数中使用的函数,但由于某种原因,我没有看到原始函数始终运行,而不是我作为模拟创建的函数。

我正在测试的代码具有这种类型的设置:

def function_being_tested(foo):
    ...
    function_i_want_to_mock(bar)
    ...

def function_i_want_to_mock(bar)
    print("Inside original function")
    ...
Run Code Online (Sandbox Code Playgroud)

我已经安装了 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)
Run Code Online (Sandbox Code Playgroud)

然后发生的事情是,当我运行测试时,我总是得到:“在原始函数内”,而不是打印的参数,因此它始终运行原始函数。

我以前使用过这个确切的设置并且它有效,所以我不确定是什么原因造成的。可能是设置错误...

如果有人有不同的方法来做到这一点或发现一些错误,我们将不胜感激。

Duš*_*ďar 12

"path.to.function.function_i_want_to_mock"应该是使用该函数的路径,而不是定义的路径。

因此,如果在您正在测试的function_i_want_to_mock地方定义moduleA.py但导入并使用,moduleB.py那么您应该使用@mock.patch("path.to.moduleB.function_i_want_to_mock", ...).

  • 这解决了!在我之前使用它时,我正在测试的内部函数与我正在嘲笑的内部函数位于同一模块中,因此这种差异对我来说是“隐藏的”。谢谢你! (2认同)