在Python中,测试函数是否抛出异常的方法有很多种。以下是一些常用的方法:
try
和except
语句:def test_function():
try:
function_to_test()
except Exception as e:
print(f"Exception caught: {e}")
assertRaises
方法:import unittest
class TestFunction(unittest.TestCase):
def test_function_raises_exception(self):
with self.assertRaises(Exception):
function_to_test()
pytest
库:import pytest
def test_function_raises_exception():
with pytest.raises(Exception):
function_to_test()
在这些方法中,您可以捕获并检查函数是否抛出了预期的异常。如果您需要测试特定的异常类型,可以将Exception
替换为所需的异常类型。