软件开发越做越大,你会发现:
- 需求改来改去
- Bug 修完又冒出来
- 函数多了后自己都不敢动
这个时候,自动化测试就是你的"安全网"。 Python 提供两个主流的单元测试框架:
- unittest(官方库,自带)
- pytest(第三方库,更现代)
这篇文章带你一次搞懂:
- unittest 的使用方式
- pytest 的核心优势
- 二者对比
- 项目中怎么选
- 实例代码示范
1. unittest:Python 自带的 xUnit 风格框架
它的特点很"企业级":
- 要写测试类
- 要继承
unittest.TestCase - 要用固定命名规则
- 断言方式很多
更像 Java、C# 那类标准单元测试体系。
unittest 基本示例
假设我们有一个待测试的函数:
python
def add(a, b):
return a + b
unittest 的写法:
python
import unittest
from main import add
class TestMath(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)
self.assertNotEqual(add(2, 3), 6)
if __name__ == "__main__":
unittest.main()
运行方式:
bash
python test_math.py
unittest 常用断言方法
| 方法 | 描述 |
|---|---|
| assertEqual(a, b) | a == b |
| assertNotEqual(a, b) | a != b |
| assertTrue(x) | x 为 True |
| assertFalse(x) | x 为 False |
| assertIn(x, y) | x in y |
| assertRaises(err, func, args) | 检查是否抛出异常 |
unittest 比较强调规范和结构,适合大型工程。
2. pytest:更 Pythonic、更现代、更香
pytest 是现在最流行的 Python 测试框架,它的目标就是------"简单,强大"。
它的特点:
- 无需写测试类
- 无需继承任何父类
- 测试文件、函数命名即可自动发现
- 断言直接用 Python 的
assert(语法自然) - 插件生态超级丰富(约 1800+)
pytest 示例
还是刚才的 add 函数:
python
def test_add():
assert add(2, 3) == 5
assert add(2, 3) != 6
运行方式:
bash
pytest
是不是清爽很多?
3. pytest 强大的功能亮点
① 断言超智能
pytest 会自动解析出详细的断言对比信息:
python
assert add(2, 3) == 10
输出:
ini
E assert 5 == 10
E + where 5 = add(2, 3)
调错体验直接拉满。
② 参数化测试(超好用)
python
import pytest
@pytest.mark.parametrize("a,b,res", [
(2, 3, 5),
(1, 1, 2),
(-1, 1, 0)
])
def test_add(a, b, res):
assert add(a, b) == res
一个函数跑多组测试数据,适用于 API 测试、算法验证。
③ Fixtures(依赖注入)
写测试时,不用重复初始化环境:
python
import pytest
@pytest.fixture
def user():
return {"name": "Tom", "age": 18}
def test_user(user):
assert user["age"] == 18
类似于 Django 的 test client、Flask 的 app fixture,都可以自动提供。
④ 覆盖率统计
bash
pytest --cov=myproject
直接生成项目的覆盖率报告。
4. unittest vs pytest 对比总结
| 对比项 | unittest | pytest |
|---|---|---|
| 是否内置 | ✔ 自带 | ❌ 需要 pip install |
| 使用风格 | 面向对象 | 更 Pythonic |
| 扩展性 | 一般 | 非常强(插件丰富) |
| 编写难度 | 偏重 | 偏轻松 |
| 自动发现 | 一般 | 很强 |
| 断言 | 专门的断言方法 | 直接用 assert |
一句话总结:
- 做小项目 → pytest
- 想写优雅测试 → pytest
- 公司项目规范要求 unittest → unittest
- 要跟 Java/CI 流程兼容 → unittest 也没问题
- 你完全有选择权 → pytest 最爽
5. 项目测试目录结构示例(pytest)
推荐结构:
markdown
project/
app/
utils/
tests/
test_utils.py
test_api.py
conftest.py
pytest 会自动识别:
- 名字以
test_开头的文件 - 名字以
test_开头的函数 - conftest.py 中的全局 fixture
6. unittest & pytest 混用可以吗?
完全可以。 pytest 能自动识别 unittest 的测试类并执行。
比如你公司的老代码用 unittest,你可以逐步迁移到 pytest,不会冲突。
7. 总结
这篇文章帮你梳理了 Python 的两大测试框架:
- unittest:规范、传统、标准化
- pytest:现代、轻松、生态强
如果你问我项目里用哪个?
99% 的情况用 pytest 因为它是真·好用,同时更适合现代 Python 工程。