1. 程式人生 > >python之單元測試_生成測試報告

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/”:謝謝!!如有疑問,歡迎大家留言區艾特我哈。