任何一种编程语言, 都会有单元测试框架, 本文介绍Python 自带的unittest模块
# -* - coding: UTF-8 -* - class Myclass: def sum(self,x,y): return x+y def sub(self, x, y): return x -y import unittest class mytest(unittest.TestCase): #初始化工作 def setUp(self): pass #退出清理工作 def tearDown(self): pass #具体的测试用例, 一定要以test开头 def testsum(self): instance = Myclass() testResult = instance.sum(3, 4) self.assertEqual(testResult, 9, '3+4 = 7, not 9, so test fail') #具体的测试用例, 一定要以test开头 def testsub(self): instance = Myclass() testResult = instance.sub(8,5) self.assertEqual(testResult, 3, 'test pass') if __name__ =='__main__': unittest.main()