unittest属于是有类继承的测试框架,扩展他的API相对要简单很多。需要在TestCase 类的基础上扩展即可,例如django框架所提供的测试类也继承自unittest的TestCase类。
如上图所示,只需要在自己的的扩展中创建TestCase类继承unittest框架的TestCase类,然后,在具体项目中使用自己的扩展TestCase类即可。
我们暂且为扩展命名为:unittest-extend。
https://github.com/defnngj/unittest-extend
目录结构如下:
unittest-extend/
├── xtest/
│ ├── __init__.py
│ ├── case.py
└── setup.py
主要功能是在case.py文件实现扩展方法。
import unittest
import random
class TestCase(unittest.TestCase):
"""
扩展unittest 的方法
"""
@staticmethod
def say_hello(name: str, times: int = 1) -> None:
"""
打招呼
:param name: 名字
:param times: 次数
:return:
"""
if times str:
"""
随机返回一个名字
:return:
"""
name_list = ["Andy", "Bill", "Jack", "Robert", "Ada", "Jane", "Eva", "Anne"]
choice_name = random.choice(name_list)
return choice_name
def run(verbosity=1):
"""
运行用例方法
"""
unittest.main(verbosity=verbosity)
主要代码说明:
-
创建
TestCase类继承unittest.TestCase类。 -
实现
say_hello()方法,针对输入的name,输出times次数的“Hello, XX”。 -
实现
get_name()方法,用于随机返回一个英文名。 -
将
unittest.main()入口方法,重写到一个run()方法中,这样做是为了完全消除编写测试用例中unittest的影子。
unittest-extend 安装方式参考项目Github地址
安装好unittest-extend之后创建测试文件test_sample.py,实现代码如下:
import xtest
class MyTest(xtest.TestCase):
def test_case(self):
self.say_hello(self.get_name, 3)
if __name__ == '__main__':
xtest.run()
主要代码说明:
-
创建测试类
MyTest继承xtest.TestCase类。 -
创建测试用例
test_case(), 在用例中使用父类中封装的say_hello()方法,然后调用父类中的get_name语句获取一个英文名,并对这个名字说三次“hello”。 -
最后,调用
xtest.run()运行测试用例。
执行结果:
> python test_sample.py
Hello Andy
Hello Andy
Hello Andy
.
----------------------------------------------------------------------
Ran 1 test in 0.002s
OK
最后,扩展unittest单元测试框架的功能并不局限于在父类中实现方法,同样可以使用装饰器、运行方法(run()方法)或者命令行参数。我们会在后续的章节中详细介绍。
