fixtures通过setup和teardown实现,除了测试用例之外,还提供类和模块的fixtures
- setUpModule/tearDownModule:在整个模块的开始与结束时被执行
- setUpClass/tearDownClass:在测试类的开始与结束时被执行
- setUp/tearDown:在测试用例的开始与结束时被执行
如下:
1 import unittest 2 3 4 def setUpModule(): 5 print('test module start') 6 7 8 def tearDownModule(): 9 print('test module end') 10 11 12 class MyTest(unittest.TestCase): 13 @classmethod 14 def setUpClass(cls): 15 print('test class start') 16 17 @classmethod 18 def tearDownClass(cls): 19 print('test class end') 20 21 def setUp(self): 22 print('test case start') 23 24 def tearDown(self): 25 print('test case end') 26 27 def test1(self): 28 print('test case1') 29 30 def test2(self): 31 print('test case2') 32 33 34 if __name__ == '__main__': 35 unittest.main()
执行结果如下:
test module start
test class start
test case start
test case1
test case end
test case start
test case2
test case end
test class end
test module end
Ran 2 tests in 0.002s
OK