【Python】【unittest】unittest测试框架中setup,teardown与setupclass,teardownclass的区别

 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)两个函数在一个用例集合执行前只会执行一次,然后再所有用例执行完成后再清空所有配置,此种用法主要用在用例之间相互没有什么影响的场景

转载于:https://www.cnblogs.com/aziji/p/9284519.html

你可能感兴趣的:(【Python】【unittest】unittest测试框架中setup,teardown与setupclass,teardownclass的区别)