小编ste*_*rey的帖子

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

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

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

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)

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

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

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

python django unit-testing python-3.x

6
推荐指数
1
解决办法
968
查看次数

标签 统计

django ×1

python ×1

python-3.x ×1

unit-testing ×1