![](/img/trans.png)
[英]Using python's mock patch.object to change the return value of a method called within another method
[英]python's mock return value of a method called within another method doesn't work
我想模擬這樣的單元測試方法:
get_tree_test.py
from company.marketing_tree import get_tree
class MidNightTests(TestCase):
@mock.patch("company.analytics.get_fb_data", autospec=True)
def test_first_midnight(self, mock_fb_data):
mock_fb_data.return_value = {}
get_tree()
get_tree.py
from company.analytics import get_fb_data
def get_tree():
executor = ThreadPoolExecutor(max_workers=2)
data_caller = executor.submit(get_data)
info_caller = executor.submit(get_info)
def get_data():
executor = ThreadPoolExecutor(max_workers=2)
first_data = exeuctor.submit(get_fb_data)
我確實看到模擬對象已創建了嘲笑對象mock_fb_data.return_value = {}
,但是當我調試get_data()
方法時,我發現get_fb_data是一個函數而不是一個模仿對象
我想念什么?
您需要在正確的地方打補丁。 在get_tree
,您創建了一個全局名稱get_fb_data
,代碼直接使用了該名稱:
from company.analytics import get_fb_data
您需要修補該名稱 ,而不是原始的company.analytics.get_fb_data
名稱; 修補工作通過替換名稱來指向模擬對象來完成:
class MidNightTests(TestCase):
@mock.patch("get_tree.get_fb_data", autospec=True)
def test_first_midnight(self, mock_fb_data):
mock_fb_data.return_value = {}
get_tree()
請參閱unittest.mock
文檔的“ 何處修補”部分 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.