(1)htmlTestRunner.py 的下载路径: https://pan.baidu.com/s/1Yk2E8d8bIo5_rmpussOE9Q 提取码: 0jae
(2)HTMLTestRunner.py 的存放到 python 安装的路径的 lib 文件夹下面, 如下图所示:
(3) 以加减乘除的计算为例, 创建三个类:(1)mathMethod.py(2)testMathMethod.py(3)testSuit.py
- (1)mathMethod.py
- class MathMethod:
- def __init__(self, a, b):
- self.a = a
- self.b = b
- def add(self):
- return self.a+self.b
- def sub(self):
- return self.a-self.b
- def chengfa(self):
- return self.a*self.b
- def div(self):
- return self.a/self.b
- (2)testMathMethod.py
- import unittest
from 单元测试. mathMethod import MathMethod
- # 对 mathmethod 进行单元测试
- # TestCase
- # 下面都是测试用例
- class TestMathMethod(unittest.TestCase):
- def setUp(self):
- print("开始测试啦!")
- def test_add(self):
- try:
- t = MathMethod(5, 4).add()
- self.assertEqual(t, 9, "出错啦")
- print(t)
- except AssertionError as e:
- print("单元测试出错啦, 错误是 %s")
- raise e
- def test_sub(self):
- try:
- t = MathMethod(9, 6).sub()
- self.assertEqual(t, 3, "出错啦")
- print(t)
- except AssertionError as e:
- print("单元测试出错啦, 错误是 %s")
- raise e
- def test_chengfa(self):
- try:
- t = MathMethod(5, 5).chengfa()
- self.assertEqual(t, 25, "出错啦")
- print(t)
- except AssertionError as e:
- print("单元测试出错啦, 错误是 %s")
- raise e
- def test_div(self):
- try:
- t = MathMethod(25, 5).div()
- self.assertEqual(t, 5, "出错啦")
- print(t)
- except AssertionError as e:
- print("单元测试出错啦, 错误是 %s")
- raise e
- def tearDown(self):
- print("测试结束了!")
- (3)testSuit.py
- import unittest
- import time
from 单元测试. testMathMethod import TestMathMethod
- import HTMLTestRunner
- # 作用把所有测试用例集合起来, 放在一个测试集里面.
- suite = unittest.TestSuite()
- suite.addTest(TestMathMethod("test_add"))
- suite.addTest(TestMathMethod("test_sub"))
- suite.addTest(TestMathMethod("test_chengfa"))
- suite.addTest(TestMathMethod("test_div"))
- now = time.strftime('%Y-%m-%d_%H_%M_%S')
- # 执行测试集
- filePath = "pyResult" + now + ".html"
- fp = open(filePath, 'wb')
- # 生成报告的 title, 描述
- runner = HTMLTestRunner.HTMLTestRunner(stream=fp, title="2019-1-6 test report",
- verbosity=2) # 执行测试用例出结果
- runner.run(suite)
- fp.close()
(4) 运行 testSuit 生成测试报告:
来源: http://www.bubuko.com/infodetail-2911006.html