2017-08-08 55 views
0

下面我有一個函數,並希望寫一個單元測試,以檢查是否我的代碼中使用模擬庫你如何測試函數拋出異常?

def get_foo(): 
    try: 
     return requests.get("http://www.bongani.com") 
    except requests.exceptions.ConnectionError: 
     print("Error") 

抓住ConnectionError我有什麼:

import unittest 
import mock 


class MyTestCase(unittest.TestCase): 
    @mock.patch('requests.get') 
    def test_foo(self, mock_requests_get): 
     mock_requests_get.side_effect = requests.exceptions.ConnectionError() 
     with self.assertRaises(requests.exceptions.ConnectionError): 
      get_foo() 

if __name__ == '__main__': 
    unittest.main() 

我得到這個錯誤:

Traceback (most recent call last): 
File "/usr/local/lib/python2.7/site-packages/mock/mock.py", line 1305 , in patched 
    return func(*args, **keywargs) 
File "<ipython-input-24-15266e4f708a>", , in test_foo 
    get_foo() 
AssertionError: ConnectionError not raised 

我想模擬return requests.get("http://www.bongani.com")行,以便在調用時引發異常

回答

0

這個異常不會冒泡(即被壓制),因爲你抓住了它,然後你沒有重新提升它。反過來,你的單元測試會失敗,因爲你正在測試你的函數在抑制它時引發了這個異常。

您可以根據所需行爲更改函數的功能或單元測試。

假設測試是正確的,然後你的函數需要重新引發異常這樣的:

def get_foo(): 
    try: 
     return requests.get("http://www.bongani.com") 
    except requests.exceptions.ConnectionError: 
     print("Error") 
     raise # <---------------- add this line 

另一種情況下,該功能是正確的,測試是錯誤的。您修復測試看起來像這樣:

class MyTestCase(unittest.TestCase): 
    @mock.patch('requests.get') 
    def test_foo(self, mock_requests_get): 
     mock_requests_get.side_effect = requests.exceptions.ConnectionError() 
     self.assertIsNone(get_foo()) # <----- no more assertRaises 
+0

我和情景2一起去了。謝謝你讓我看到我的錯誤。 –

0

確保您修補正確的路徑

@mock.patch('path.to.get_foo.requests.get') 

你不想實例除外。

mock_requests_get.side_effect = requests.exceptions.ConnectionError 
+0

仍然得到相同的結果。 –