unittest是python自带的一个标准木块,单元测试框架
unittest基本使用方法:
- 我们需要先导入unittest (import unittest)
import unittest
- 定义一个继承unittest.TestCase的测试用例类
class TestFun(unittest.TestCase):
- 定义setUp和tearDown
def setUp(self): print 'do before ....' def tearDown(self): print 'do after....'
- 定义测试用例,以test开头。如testAdd
def testAdd(self): print 'test add...' self.assertEqual(2,addNum(1,1))
- 一个测试用例只写一个功能,目标和测试内容需明确。
- 单元测试的加载方式有2种:一种是通过unittest.main()来启动单元测试的测试模块;一种是添加到testsuite集合中再加载所有的被测试对象,而testsuit里存放的就是单元测试的用例
if __name__=="__main__": suite=unittest.TestLoader.loadTestsFromTestCase(TestFun) unittest.TextTestRunner(verbosity=2).run(suite)
if __name__=="__main__": unittest.main()
unittest模块的常用方法:
- assertEqual(a, b) a == b
- assertNotEqual(a, b) a != b
- assertTrue(x) bool(x) is True
- assertFalse(x) bool(x) is False
- assertIs(a, b) a is b 2.7
- assertIsNot(a, b) a is not b 2.7
- assertIsNone(x) x is None 2.7
- assertIsNotNone(x) x is not None 2.7
- assertIn(a, b) a in b 2.7
- assertNotIn(a, b) a not in b 2.7
- assertIsInstance(a, b) isinstance(a, b) 2.7
- assertNotIsInstance(a, b) not isinstance(a, b) 2.7
实例代码:
1 import unittest 2 def addNum(a,b): 3 return a+b 4 def delNum(a,b): 5 return a-b 6 class TestFun(unittest.TestCase): 7 def setUp(self): 8 print 'do before ....' 9 def tearDown(self): 10 print 'do after....' 11 def testAdd(self): 12 print 'test add...' 13 self.assertEqual(2,addNum(1,1)) 14 def testDel(self): 15 print 'test del' 16 self.assertEqual(0,delNum(1,1)) 17 if __name__=="__main__": 18 unittest.main()