Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีทดสอบว่าฟังก์ชัน Python โยน Exception ที่คาดหวัง

ใช้โมดูล unittest และ assertRaises เพื่อตรวจสอบว่าโค้ดบล็อกโยน exception ที่คาดหวัง

ตัวอย่าง

import unittest

class MyTestCase(unittest.TestCase):
    def test_1_cannot_add_int_and_str(self):
        with self.assertRaises(TypeError):
            1 + '1'

    def test_2_cannot_add_int_and_str(self):
        import operator
        self.assertRaises(TypeError, operator.add, 1, '1')

unittest.main(exit=False)

ผลลัพธ์

..
----------------------------------------------------------------------
Ran 2 tests in 0.001s
OK

assertRaises ใช้เป็น context manager (with) จะจัดการ exception ให้อัตโนมัติ หรือเรียกแบบฟังก์ชันส่ง exception type, callable, และ arguments ต่อไป