我有以下代码,想在给定函数引发“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)
关于python - 在 python 中对 "FileNotFoundError"进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26918331/