13. 原生測試框架Unittest解決用例組織問題 與測試套件的使用
一、測試架構核心組件解析
1.1 系統組成模塊
1.2 關鍵組件功能對照表
組件 | 功能描述 | 對應代碼實現 |
---|
TestLoader | 掃描發現測試用例 | unittest.defaultTestLoader |
TestSuite | 裝載測試集合容器 | unittest.TestSuite() |
TextTestRunner | 執行測試并輸出結果 | unittest.TextTestRunner() |
TestCase | 測試用例基類 | unittest.TestCase |
二、測試發現機制詳解
2.1 路徑配置實現
CASE_PATH = join(dirname(__file__), './chap4/case')
路徑處理要點:
- 使用
os.path
保證跨平臺兼容性 - 相對路徑轉換為絕對路徑
- 支持多級目錄結構掃描
2.2 測試加載流程
for test in tests:test_suit = loader.discover(start_dir=CASE_PATH, pattern=test )suit.addTest(test_suit)
discover方法參數解析:
參數 | 值示例 | 作用說明 |
---|
start_dir | ‘./chap4/case’ | 測試代碼根目錄 |
pattern | ‘test_*.py’ | 文件匹配模式(支持通配符) |
top_level_dir | None | 項目頂層目錄(可選) |
三、測試執行控制體系
3.1 運行器配置參數
runner = unittest.TextTestRunner(verbosity=2
)
verbosity級別說明:
級別 | 輸出內容 | 適用場景 |
---|
0 | 僅顯示總測試數/失敗數 | 簡潔模式 |
1 | 顯示進度點(默認) | 常規執行 |
2 | 顯示完整用例名稱/錯誤詳情 | 調試排查 |
3.2 測試執行流程
四、測試組織結構優化
4.1 多模塊加載配置
tests = ['test_module_1.py', 'test_module_2.py'
]
組織策略對比:
策略類型 | 示例 | 特點 |
---|
模塊粒度 | test_*.py | 按功能模塊劃分 |
類粒度 | ClassName | 按測試場景劃分 |
方法粒度 | test_methodName | 精確控制單個測試 |
4.2 執行范圍控制
tests = ['test_*.py', 'TestClass', 'module.TestClass.test_method'
]
五、工程化實踐建議
5.1 目錄結構規范
project/
├── src/ # 源碼目錄
├── tests/ # 測試目錄
│ ├── __init__.py # 測試配置
│ ├── module1/ # 模塊測試包
│ └── module2/
└── runner.py # 統一執行入口
5.2 擴展執行能力
from HTMLTestRunner import HTMLTestRunner
runner = HTMLTestRunner(output='report.html',verbosity=2
)
六、完整代碼
"""
Python :3.13.3
Selenium: 4.31.0start.py
"""
from os.path import join, dirname
import unittest
from chap4.case import testsCASE_PATH = join(dirname(__file__), './chap4/case')
suit = unittest.TestSuite()
loader = unittest.defaultTestLoader
for test in tests:test_suit = loader.discover(start_dir=CASE_PATH, pattern=test)suit.addTest(test_suit)
runner = unittest.TextTestRunner(verbosity=2)
runner.run(suit)
"""
Python :3.13.3
Selenium: 4.31.0test_module_1.py
"""import unittestclass A(unittest.TestCase):def test_a1(self):self.assertEqual(1,2)def test_a2(self):...class B(unittest.TestCase):def test_b1(self):...def test_b2(self):...
"""
Python :3.13.3
Selenium: 4.31.0test_module_2.py
"""import unittestclass C(unittest.TestCase):def test_a1(self):...def test_a2(self):...class D(unittest.TestCase):def test_b1(self):...def test_b2(self):...
"""
Python :3.13.3
Selenium: 4.31.0__init__.py
"""tests = ['test_module_1.py','test_module_2.py'
]
「小貼士」:點擊頭像→【關注】按鈕,獲取更多軟件測試的晉升認知不迷路! 🚀