[英]Unit testing for “FileNotFoundError” in python
我有以下代碼,並且當給定函數為“FileNotFoundError”引發時,它想要解開
def get_token():
try:
auth = get_auth() # This function returns auth ,if file exists else throws "FileNotFoundError
except FileNotFoundError:
auth= create_auth()
return auth
我無法弄清楚如何測試引發“FileNotFoundError”並且不調用create_auth的情況。
任何提示都將不勝感激
謝謝
在單元測試中,您需要模擬get_auth
函數並使其通過使用.side_effect
屬性引發FileNotFoundError
:
@mock.patch('path.to.my.file.get_auth')
def test_my_test(self, mock_get_auth):
mock_get_auth.side_effect = FileNotFoundError
然后,您可以測試是否實際調用了create_auth
:
@mock.patch('path.to.my.file.create_auth')
@mock.patch('path.to.my.file.get_auth')
def test_my_test(self, mock_get_auth, mock_create_auth):
mock_get_auth.side_effect = FileNotFoundError
get_token()
self.assertTrue(mock_create_auth.called)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.