繁体   English   中英

来自另一个文件/模块的 Python 模拟补丁

[英]Python Mock Patch From Another File/Module

我有一个按预期工作正常的模拟。

from mock import patch

def second(arg):
    return 3


def first():
    return second('arg')


@patch('test.second')
def test_test(second_mock):
    second_mock.return_value = 47  # We decide this

    call_it = first()

    second_mock.assert_called_once()
    second_mock.assert_called_with('arg')

    assert call_it == 47

但是,如果我将 second() 方法移到另一个文件中,则不会...

from mock import patch
from test_help import second


def first():
    return second('arg')


@patch('test_help.second')
def test_test(second_mock):
    second_mock.return_value = 47  # We decide this

    call_it = first()

    second_mock.assert_called_once()
    second_mock.assert_called_with('arg')

    assert call_it == 47

我得到了同样的错误:AssertionError: Expected 'second' to have been called once. 调用了 0 次。

我在这里缺少什么?

我尝试了几种不同的格式化方式,但似乎都不起作用。 在这种情况下,这甚至是单元测试的最佳实践/包吗?

别担心,你在正确的道路上,这就是模拟函数的方法。

关于您的probem,请记住您根据调用模拟函数的函数修补命名空间。

因此,当您在模块module_where_first_is_located from test_help import second进行from test_help import second个被识别为module_where_first_is_located.second

所以,而不是@patch('test_help.second')@patch('module_of_first.second')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM