“的单元测试”;FileNotFoundError";用python
我有下面的代码,希望在给定函数引发“FileNotFoundError”时进行测试“的单元测试”;FileNotFoundError";用python,python,unit-testing,python-3.x,mocking,Python,Unit Testing,Python 3.x,Mocking,我有下面的代码,希望在给定函数引发“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 我不知道如何测试它引发“FileNotFound
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\u auth的情况
任何暗示都将不胜感激
谢谢在单元测试中,您需要模拟
get\u auth
函数,并使用属性使其引发FileNotFoundError
。副作用
属性:
@mock.patch('path.to.my.file.get_auth')
def test_my_test(self, mock_get_auth):
mock_get_auth.side_effect = FileNotFoundError
然后,您可以测试是否实际调用了create\u 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)