a.测试驱动开发:(TDD:Test-Driven Development)
b.单元测试是用来对一个模块、一个函数或者一个类来进行正确性检验的测试工作。
c.以test开头的方法就是测试方法
d.模块函数:
检查预期结果:assertEqual()
验证条件:assertTrue()或 assertFalse()
验证是否引发了特定异常:assertRaises()
在每个测试方法之前和之后执行的指令:setUp()和tearDown()
为测试脚本提供命令行界面: unittest.main()
mydict.py:
#!/usr/bin/python # -*- coding: utf-8 -*- class Dict(dict): def __init__(self, **kw): super().__init__(**kw) def __getattr__(self, key): try: return self[key] except KeyError: raise AttributeError(r"'Dict' object has no attribute '%s'" % key) def __setattr__(self, key, value): self[key] = value
mydict_test.py:
#!/usr/bin/python # -*- coding: utf-8 -*- import unittest from mydict import Dict class TestDict(unittest.TestCase): def setUp(self): print('setUp...') def tearDown(self): print('tearDown...') def test_init(self): d = Dict(a=1, b='test') self.assertEqual(d.a, 1) self.assertEqual(d.b, 'test') self.assertTrue(isinstance(d, dict)) def test_key(self): d = Dict() d['key'] = 'value' self.assertEqual(d.key, 'value') def test_attr(self): d = Dict() d.key = 'value' self.assertTrue('key' in d) self.assertEqual(d['key'], 'value') def test_keyerror(self): d = Dict() with self.assertRaises(KeyError): value = d['empty'] def test_attrerror(self): d = Dict() with self.assertRaises(AttributeError): value = d.empty
运行单元测试
一旦编写好单元测试,我们就可以运行单元测试。最简单的运行方式是在mydict_test.py
的最后加上两行代码:
if __name__ == '__main__': unittest.main()
这样就可以把mydict_test.py
当做正常的python脚本运行:
$ python mydict_test.py
另一种方法是在命令行通过参数-m unittest
直接运行单元测试:
$ python -m unittest mydict_test ..... ----------------------------------------------------------------------Ran 5 tests in 0.000sOK