我们有时候需要断言一些方法会抛出异常,这些异常需要符合我们的预期。
新建test_exception.py文件,内容如下
import unittest
class DivZeroTestCase(unittest.TestCase):
    def test_should_raise_exception(self):
        with self.assertRaises(ZeroDivisionError):
            1 / 0
if __name__ == ‘__main__‘:
    unittest.main()
$ python test_exception.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
ZeroDivisionErrorwith语句加assertRaises,assertRaises的参数中传入预期的异常(这些异常可能需要先import进来),在with的子句中放上会抛出异常的语句或表达式参考
http://www.testclass.net/pyunit/assert_raise
断言异常方法,实际运行的时候发生期望的异常,属于测试通过。
原文:https://www.cnblogs.com/candyYang/p/12290370.html