下面我有一個函數,並希望寫一個單元測試,以檢查是否我的代碼中使用模擬庫你如何測試函數拋出異常?
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")
行,以便在調用時引發異常
我和情景2一起去了。謝謝你讓我看到我的錯誤。 –