unittest框架是一个python自带的测试框架,主要包含以下部分:
test fixture初始化方法的执行顺序
# 导入unittest
import unittest
# 创建测试类
import unittest
# 创建测试类
class MyTestCase(unittest.TestCase): # 继承TestCase类
def setUp(self):
print("测试准备")
def tearDown(self):
print("测试结束")
@classmethod # 定义setUpClass和tearDownClass方法必须在前面添加@classmethod装饰器
def setUpClass(cls):
print("测试类准备")
@classmethod
def tearDownClass(cls):
print("测试类结束")
# 以上为test fixture 部分
def test_something1(self):
print("test1")
def test_something2(self):
print("test2")
# 以上为test case部分(case的命名必须以 test_ 开头)
if __name__ == '__main__':
unittest.main()
执行结果:
Testing started at 14:09 ...
"D:\Program Files (x86)\Python37-32\python.exe" "D:\Program Files\JetBrains\PyCharm 2019.2.1\helpers\pycharm\_jb_unittest_runner.py" --path E:/test/demo/demo2.py
Launching unittests with arguments python -m unittest E:/test/demo/demo2.py in E:\test\demo
测试类准备
测试准备
test1
测试结束
测试准备
test2
测试结束
测试类结束
Ran 2 tests in 0.005s
OK
Process finished with exit code 0
以上代码可以看到setUpclass在类方法被调用前首先执行,且只执行一次;tearDownClass最后执行,也执行一次;setUp在每个case执行前执行,tearDown在每个case执行后执行
多个测试case可以用test suit测试套件来组织用例
import unittest
from demo import demo3
from demo import demo4
#构造测试集
suite = unittest.TestSuite()
suite.addTest(demo3.MyTest1('test_something1'))
suite.addTest(demo4.MyTest2('test_something2'))
if __name__=='__main__':
#test runner执行测试
runner = unittest.TextTestRunner()
runner.run(suite)
注:要在demo包下创建demo3.py和demo4.py,在两个py里创建两个测试类MyTest1和MyTest2,分别封装两个测试方法test_something1和test_something2
执行结果:
..
----------------------------------------------------------------------
Ran 2 tests in 19.320s
OK
Process finished with exit code 0