1 # -*- coding:utf-8 -*- 2 import unittest 3 4 5 def runTest(testcaseclass,testcase=[]): 6 suite = unittest.TestSuite() 7 for case in testcase: 8 suite.addTest(testcaseclass(case)) 9 unittest.TextTestRunner().run(suite) 10 11 class test(unittest.TestCase): 12 13 def setUp(self): 14 print 'This is the setup msg' 15 16 def tearDown(self): 17 print 'This is the teardown msg' 18 @classmethod 19 def setUpClass(cls): 20 print 'this is the setupclass msg' 21 22 23 @classmethod 24 def tearDownClass(cls): 25 print 'this is the teardownclass msg' 26 27 def test1(self): 28 print 'This is the first testcase' 29 30 def test2(self): 31 print 'This is the second testcase' 32 33 def test3(self): 34 print 'This is the third testcase' 35 36 runTest(test,['test2','test3','test1']) 37 38 39 輸出如下: 40 C:\Python27\python.exe "E:/Project/A3A 8 4G/13.py" 41 ... 42 43 ---------------------------------------------------------------------- 44 45 46 this is the setupclass msg 47 This is the setup msg 48 This is the second testcase 49 50 This is the teardown msg 51 52 This is the setup msg 53 This is the third testcase 54 This is the teardown msg 55 This is the setup msg 56 This is the first testcase 57 This is the teardown msg 58 this is the teardownclass msg 59 60 Ran 3 tests in 0.000s 61 62 OK 63 64 Process finished with exit code 0
總結:
1、setup()和teardown()兩個函數在每條測試用例執行時都會進行重復執行一次,該場景針對那些測試用例間有相互影響的場景,才需要在每執行一條新用例時進行一次初使化,執行完畢后再清空所有配置
2、setupclass(cls)和teardownclass(cls)兩個函數在一個用例集合執行前只會執行一次,然后再所有用例執行完成后再清空所有配置,此種用法主要用在用例之間相互沒有什么影響的場景