看了看Python中的单元测试流程, 写了个测试代码来看整体的测试流程
总结如下
- 一个 test case 类应该派生自 unittest.TestCase
- 正常的的test case的调用顺序为
- 子类TestCase可以注册自己的清理函数(my_cleanup). 这个清理函数会在teardown之后被调用
def setUp(self): super(MyTestCase, self).setUp() self.addCleanup(self.my_cleanup)
- 单元测试函数名必须以"test_"开始
def test_case_1(self): print("++++ test case 1")
测试的源代码:
from __future__ import print_function import unittest def setUpModule(): print("setUpModule") def tearDownModule(): print("tearDownModule") class MyTestCase(unittest.TestCase): def setUp(self): super(MyTestCase, self).setUp() self.addCleanup(self.my_cleanup) print() print("++++ setup") def tearDown(self): super(MyTestCase, self).tearDown() print("++++ tearDown") raise Exception() def my_cleanup(self): print("++++ my_cleanup") def test_case_1(self): print("++++ test case 1") def test_case_2(self): print("++++ test case 2") @classmethod def setUpClass(cls): print("setUpClass") @classmethod def tearDownClass(cls): print() print("tearDownClass")
这个程序的运行结果:
setUpModule setUpClass ++++ setup ++++ test case 1 ++++ tearDown ++++ my_cleanup ++++ setup ++++ test case 2 ++++ tearDown ++++ my_cleanup tearDownClass tearDownModule
时间: 2024-10-06 00:22:52