unittest框架-优化一【变量参数化】

1、新建unittest_case2文件

 1 import unittest
 2 from project.math_method import MathMethod
 3 
 4 
 5 class AddTest(unittest.TestCase):  # 测试加法类
 6     def setUp(self):
 7         print("------------开始测试啦!!!--------")
 8         self.t = MathMethod()
 9 
10     def tearDown(self):
11         print("------------测试完成啦!!!--------")
12 
13     # 变量参数化
14     def __init__(self, a, b, excepted, title, methodName):
15         super(AddTest, self).__init__(methodName)  # 超继承父类TestCase中的初始化函数
16         self.a = a
17         self.b = b
18         self.excepted = excepted
19         self.title = title
20 
21     def test_add(self):
22         print('正在执行的测试用例是{}'.format(self.title))
23         print('a的值是{}'.format(self.a))
24         print('b的值是{}'.format(self.b))
25         print('expected的值是{}'.format(self.expected))
26         res = self.t.add(self.a, self.b)  # 计算出的实际结果
27         try:
28             self.assertEqual(self.excepted, res)
29             print("两数相加结果是:{}".format(res))
30         except Exception as e:
31             print("测试出错了,错误是:{}".format(e))
32             raise e
View Code

2、新建unittest_suite2文件

 1 import unittest
 2 from project.unittest_case2 import AddTest  # 导入测试加法类
 3 from HTMLTestRunnerNew import HTMLTestRunner
 4 
 5 
 6 # *******************加载测试用例并执行,最后生成测试报告(txt/html格式)**************
 7 
 8 ########### 创建实例#########
 9 suite = unittest.TestSuite()
10 
11 ##########加载测试用例##########
12 # TestSuite加载测试用例【以实例形式】
13 # 参数化一:【测试数据在实例中列举出来】
14 # suite.addTest(AddTest(2,3,5,"两个正数相加","test_add"))
15 # suite.addTest(AddTest(-2,-3,-5,"两个负数相加","test_add"))
16 
17 # 参数化二:【测试数据已列表的形式存放在test_data中】
18 test_data=[[0,0,0,"两个0相加"],
19            [1,2,3,"两个正数相加"],
20            [-1,-2,-3,"两个负数相加"],
21            [-1,4,3,"一正一负相加"],
22            [-9,0,-9,"一正一0相加"],
23            [5,0,5,"一负一0相加"]]
24 for item in test_data:
25     suite.addTest(AddTest(item[0], item[1], item[2],item[3], "test_add"))
26 
27 # ########HTMLTestRunner执行测试用例,并生成报告(html)##############
28 with open("test_resul.html", 'wb+') as file:
29     runner = HTMLTestRunner(stream=file,
30                             verbosity=2,
31                             title='接口测试报告',
32                             description=None,
33                             tester='lc')
34     runner.run(suite)
View Code
原文地址:https://www.cnblogs.com/lctest/p/12133437.html