如何测试 Python 函数是否引发异常?
要测试 Python 函数是否抛出异常,可以使用unittest模块assertRaises方法pytest框架的raisesfu
unittest
assertRaises
pytest
raises
你可以使用以下方法unittest来测试函数是否引发异常:
unittest.TestCase
import unittest def divide(a, b): if b == 0: raise ValueError("Cannot divide by zero") return a / b class TestDivision(unittest.TestCase): def test_divide_by_zero(self): with self.assertRaises(ValueError) as context: divide(10, 0) self.assertEqual(str(context.exception), "Cannot divide by zero") if __name__ == "__main__": unittest.main()
with self.assertRaises(ExceptionType)
ExceptionType
context.exception
如果您正在使用pytest,则可以使用该raises函数来实现类似的目的:
import pytest def divide(a, b): if b == 0: raise ValueError("Cannot divide by zero") return a / b def test_divide_by_zero(): with pytest.raises(ValueError, match="Cannot divide by zero"): divide(10, 0)
pytest.raises(ExceptionType, match="Expected message")
match
assertRaises``unittest
raises``pytest