1. 程式人生 > 其它 >Python-unittest-單元測試

Python-unittest-單元測試

第一種方式

import unittest
from day07.單元測試應用2 import TestLogin #匯入測試用例類名

suite=unittest.TestSuite()#例項化測試套件
suite.addTest(TestLogin('test_login_success'))#一次新增一條測試用例,addTest(用例類名('用例名'))



suite.addTests([TestLogin('test_login_error_pwd'),TestLogin('test_login_empty_name')])#addTests新增多條測試用例,其引數需要維護為一個序列,可以是元組也可以是列表。
# f=open('result_01.txt','a',encoding='utf-8')#開啟一個檔案流物件 with open('result_01.txt','a',encoding='utf-8') as f: runner=unittest.TextTestRunner(stream=f)#例項化TextTestRunner,該類繼承了TestRunner runner.run(suite)#run使用的是其父類的run方法

 

第二種方式

#將所有的用例檔案的名稱改為以test開頭
#將HTMLTestRunner檔案放在自己的python的安裝路徑下,最好放在Lib目錄下的site_packages中
import unittest from HTMLTestRunner import HTMLTestRunner#第三方的包 suite=unittest.TestSuite()#例項化測試套件 loader=unittest.TestLoader()#例項化用例載入器 #discover要求的是在該路徑下查詢所有以test開頭的py檔案。 suite.addTests(loader.discover('../day07'))#測試用例檔案用test開頭命名 with open('test_report.html','ab') as f:#ab中a為append,b為binary runner=HTMLTestRunner(stream=f,title='
自動化測試',description='我就是來試試看的') runner.run(suite)#run方法是HTMLTestRunner中的例項方法,需要傳遞一個實參【用例或者套件】

第三種方式

將BeautifulReport檔案放在自己python的安裝路徑下Lib/site_packages中
import unittest
from BeautifulReport import BeautifulReport

loader=unittest.TestLoader()#載入器
suite=loader.discover('../day07')#生成測試套件

bf=BeautifulReport(suite)#例項化BeautifulReport物件
bf.report('自動化測試報告','report') #report是BeautifulReport的例項方法