知道unittest单元测试框架的朋友应该都知道,
执行继承了unittest.TestCase的类下每个test开头的方法(就是用例)时,都会执行setUp和tearDown,如下面的例子所示:
import unittest class TestSetupTeardown(unittest.TestCase): def setUp(self): print('连接数据库成功...') def tearDown(self): print('关闭数据库。') def test_a(self): print('test_a') def test_b(self): print('test_b') if __name__ == '__main__': unittest.main()
setUp连接数据库,tearDown关闭数据库,这样反复执行,无疑是会增加数据库服务器资源的损耗,且浪费时间
能不能只执行一次呢?
答案是肯定的,通过装饰器就可以实现
import unittest class TestSetupTeardown(unittest.TestCase): @classmethod def setUpClass(cls): print('连接数据库成功...') @classmethod def tearDownClass(cls): print('关闭数据库。') def test_a(self): print('test_a') def test_b(self): print('test_b') if __name__ == '__main__': unittest.main()
import unittest
class TestSetupTeardown(unittest.TestCase):
@classmethod
def setUpClass(cls):
print('连接数据库成功...')
@classmethod
def tearDownClass(cls):
print('关闭数据库。')
def test_a(self):
print('test_a')
def test_b(self):
print('test_b')
if __name__ == '__main__':
unittest.main()