python之单元测试_生成测试报告

(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生成测试报告:

 

请大家支持原创,尊重原创,如要转载,请注明出处:“转载自https://www.cnblogs.com/xiaoyunyun100fen/”:谢谢!!如有疑问,欢迎大家留言区艾特我哈。

posted @ 2019-01-06 16:16  小云云100分  阅读(828)  评论(0编辑  收藏  举报