Python 自动化测试实战:unittest vs pytest 哪个更好?
Introduction
写 Python 测试绕不开两个框架:
- <strong>unittest</strong> — Python 标准库,自带,无需安装
- <strong>pytest</strong> — 第三方框架,以简洁著称,插件极其丰富
两者都能完成测试任务,但写法和生态差异很大。本文从多维度对比,帮你做出选择。
---
基础语法对比
unittest(标准库)
import unittest
class TestMathOperations(unittest.TestCase):
def setUp(self):
"""每个测试前执行"""
self.values = (1, 2)
def tearDown(self):
"""每个测试后执行"""
pass
def test_addition(self):
self.assertEqual(sum(self.values), 3)
def test_multiplication(self):
a, b = self.values
self.assertEqual(a * b, 2)
运行:
python -m unittest test_sample.py -v
pytest(第三方)
import pytest
@pytest.fixture
def values():
return (1, 2)
def test_addition(values):
assert sum(values) == 3
def test_multiplication(values):
a, b = values
assert a * b == 2
运行:
pytest test_sample.py -v
---
全面对比
| 特性 | unittest | pytest |
|------|----------|--------|
| 安装 | 无需(标准库) | 需 pip install |
| 断言 | assertEqual/aIn/bIn... | 原生 assert |
| fixtures | setUp/tearDown | @pytest.fixture |
| 参数化 | 需第三方库 | @pytest.mark.parametrize |
| 插件生态 | 少 | 极其丰富 |
| 学习曲线 | 较陡(类写法) | 平缓(函数写法) |
---
常见问题
Q1: 项目里已经用了 unittest,能迁移到 pytest 吗?
能!pytest 完全兼容 unittest,用pytest test_sample.py 直接运行 unittest 风格的测试,无需改一行代码。
Q2: 什么时候用 unittest ?
- 要求零依赖(不能装第三方包)
- 团队约定用 unittest
- 测试规模小、简单
Q3: 什么时候用 pytest ?
- 需要参数化测试
- 需要丰富的插件(覆盖率、并行、HTML报告)
- 测试规模大、需要灵活的 fixtures
- 希望测试代码更简洁
Q4: 可以混用吗?
可以!pytest 可以直接运行 unittest.TestCase 子类,测试报告统一。
---
pytest 的生态优势
pytest 的插件是它最大的护城河:
# 覆盖率
pip install pytest-cov
pytest --cov=myproject
# HTML 报告
pip install pytest-html
pytest --html=report.html
# 并行执行
pip install pytest-xdist
pytest -n 4 # 4个进程并行跑
# 失败重试
pip install pytest-rerunfailures
pytest --reruns=3
---
延伸阅读
- [[pytest 快速入门]] — 第一个测试用例这样写
- [[pytest Fixtures 详解]] — 测试夹具的创建与作用域
- [[GitHub Actions 自动化测试]] — Push 就跑测试的 CI 配置
---
有问题欢迎在评论区交流!