2016-12-14 174 views
0

我想嘲笑了一種這樣的單元測試:Python的模擬返回值

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 = {}作爲模擬對象創建的,但磨片n我調試get_data()方法我看到,get_fb_data是一個函數,而不是模擬

我錯過了什麼?

回答

2

您需要修補正確的位置。裏面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文檔的Where to patch section

+0

非常感謝! – Dejell