自动化测试入门:从零搭建你的第一个测试框架
为什么需要自动化测试?
在快速迭代的软件开发中,手动测试不仅耗时且容易出错。自动化测试能显著提升回归效率,确保代码质量。本文将手把手带你从零搭建一个基于 Python 的轻量级测试框架,涵盖单元测试和集成测试。
步骤1:环境准备
确保你的系统已安装 Python 3.9+。我们使用 pytest 作为测试运行器,requests 用于接口测试。
bash pip install pytest requests
步骤2:创建项目结构
良好的目录结构是框架的基础。建议如下:
my_test_framework/ ├── tests/ │ ├── test_unit.py │ └── test_integration.py ├── utils/ │ └── api_client.py └── pytest.ini
步骤3:编写单元测试
在 tests/test_unit.py 中,测试一个简单的计算器模块。
python
calculator.py
def add(a, b): return a + b
def divide(a, b): if b == 0: raise ValueError("Cannot divide by zero") return a / b
python
tests/test_unit.py
import pytest from calculator import add, divide
def test_add(): assert add(2, 3) == 5
def test_divide(): assert divide(10, 2) == 5
def test_divide_by_zero(): with pytest.raises(ValueError): divide(1, 0)
步骤4:编写集成测试
集成测试验证多个模块的协作。假设我们有一个简单的 API 客户端。
python
utils/api_client.py
import requests
class APIClient: def init(self, base_url): self.base_url = base_url
def get_user(self, user_id):
return requests.get(f"{self.base_url}/users/{user_id}")
python
tests/test_integration.py
from utils.api_client import APIClient
def test_get_user(): client = APIClient("https://jsonplaceholder.typicode.com") response = client.get_user(1) assert response.status_code == 200 assert response.json()["id"] == 1
步骤5:配置 pytest
在 pytest.ini 中定义测试发现规则和标记。
ini [pytest] testpaths = tests addopts = -v --tb=short markers = unit: 单元测试 integration: 集成测试
步骤6:运行测试
在终端执行:
bash pytest -m unit pytest -m integration
使用 -m 可以按标记运行特定类型的测试。
步骤7:生成测试报告
安装 pytest-html 生成可视化报告:
bash pip install pytest-html pytest --html=report.html --self-contained-html
步骤8:持续集成
将测试集成到 CI/CD 流程中。以 GitHub Actions 为例,创建 .github/workflows/test.yml:
yaml name: Run Tests on: [push] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Set up Python uses: actions/setup-python@v4 with: python-version: '3.11' - name: Install dependencies run: pip install -r requirements.txt - name: Run tests run: pytest
总结
通过以上 8 个步骤,你已搭建起一个可扩展的自动化测试框架。记住,好的测试应该快速、独立且可重复。随着项目增长,可逐步引入 fixture、参数化测试和 mock 等高级特性。
开始编写你的第一个测试用例吧!