簡體   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