unittest是python标准库,从2.1开始就有。
标准的使用流程:
1:实现一个unittest.TestCase的子类
2:在其中定义以_test开头的实例函数
3:用unittest.main()来运行测试
简单的例子:
1 >>> import unittest 2 >>> def multiply(a,b): 3 ... return a*b 4 ... 5 >>> class TestUM(unittest.TestCase): 6 ... def setUp(self): 7 ... pass 8 ... def test_number(self): 9 ... self.assertEqual(multiply(3,4),12) 10 ... def test_string(self): 11 ... self.assertEqual(multiply('a',3),'aaa') 12 ... 13 >>> unittest.main() 14 .. 15 ---------------------------------------------------------------------- 16 Ran 2 tests in 0.001s 17 18 OK
注意1:其中用到的方法,其总结表如下:
注意2:当定义了setUp()函数后,在运行各部分test前会先执行此方法。同理,如果定义了一个叫tearDown()的函数的话,此函数会在所有test完成后运行。