(1)当类里面定义了 setUp() 方法的时候,测试程序会在执行每条测试项前先调用此方法;
同样地,在全部测试项执行完毕后,tearDown() 方法也会被调用。验证如下:
import unittest class SimpleTest(unittest.TestCase): def setUp(self): self.foo = list(range(10)) print(self.foo) print("="*30) def test_1st(self): self.assertEqual(self.foo.pop(), 9) print(self.foo) print("+"*30) def test_2nd(self): self.assertEqual(self.foo.pop(), 9) print(self.foo) if __name__ == '__main__': unittest.main()
- [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
- ==============================
- [0, 1, 2, 3, 4, 5, 6, 7, 8]
- ++++++++++++++++++++++++++++++
- [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
- ==============================
- [0, 1, 2, 3, 4, 5, 6, 7, 8]
注意这里两次测试均对同一个实例属性 self.foo 进行了 pop() 调用,但测试结果均为 pass,即说明,test_1st 和 test_2nd 在调用前都分别调用了一次 setUp()。
(2)如果我们想全程只调用一次 setUp/tearDown 该怎么办呢?就是用 setUpClass() 和 tearDownClass() 类方法啦。注意使用这两个方法的时候一定要用 @classmethod 装饰器装饰起来:
import unittest class SimpleTest(unittest.TestCase): @classmethod def setUpClass(self): self.foo = list(range(10)) print(self.foo) print("="*30) def test_1st(self): self.assertEqual(self.foo.pop(), 9) print(self.foo) def test_2nd(self): self.assertEqual(self.foo.pop(), 8) print(self.foo) @classmethod def tearDownClass(self): print('\t') print('+'*30) if __name__ == '__main__': unittest.main()
- [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
- ==============================
- ++++++++++++++++++++++++++++++
- [0, 1, 2, 3, 4, 5, 6, 7, 8] test_1st
- [0, 1, 2, 3, 4, 5, 6, 7] test_2nd
这个例子里我们使用了一个类级别的 setUpClass() 类方法,并修改了第二次 pop() 调用的预期返回值。运行结果显示依然是全部通过,即说明这次在全部测试项被调用前只调用了一次 setUpClass()
(3)我们希望在整个文件级别上只调用一次 setUp/tearDown,这时候就要用 setUpModule() 和 tearDownModule() 这两个函数了,注意是函数,与 TestCase 类同级:
import unittest import time def setUpModule(): print('集成测试------开始') print('') def tearDownModule(): print('集成测试------结束') print('') class SimpleTest1(unittest.TestCase): def test_1st(self): print('单元测试1---step1') time.sleep(1) def test_2nd(self): print('单元测试1---step1') time.sleep(1) class SimpleTest2(unittest.TestCase): def test_3st(self): print('单元测试2---step3') time.sleep(1) def test_4nd(self): print('单元测试2---step4') time.sleep(1) if __name__ == '__main__': unittest.main()
- 集成测试------开始
- 单元测试1---step1
- 单元测试1---step1
- 单元测试2---step3
- 单元测试2---step4
- 集成测试------结束
一般 assert*() 方法如果抛出了未被捕获的异常,那么这条测试用例会被记为 fail,测试继续进行。但如果异常发生在 setUp() 里,就会认为测试程序自身存在错误,后面的测试用例和 tearDown() 都不会再执行。即,tearDown() 仅在 setUp() 成功执行的情况下才会执行,并一定会被执行。
本文参考:
https://blog.csdn.net/yockie/article/details/47415265