Python 编程实战:unittest 与 pytest 测试框架

软件开发越做越大,你会发现:

  • 需求改来改去
  • 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 工程。


相关推荐
人工智能AI技术17 小时前
【Agent从入门到实践】18 脚本化编程:批量执行、自动化逻辑
人工智能·python
摘星编程17 小时前
React Native + OpenHarmony:MapView自定义标注样式
python
向量引擎17 小时前
[硬核架构] 2026 企业级 AI 网关落地指南:从“连接超时”到“秒级响应”的架构演进(附 Python/Java 源码)
人工智能·python·gpt·ai作画·架构·aigc·api调用
0思必得018 小时前
[Web自动化] Selenium模拟用户的常见操作
前端·python·selenium·自动化
凡客丶18 小时前
Windows版Miniconda打包环境迁移到内网离线环境【详解】
windows·python
AI大佬的小弟18 小时前
【详细步骤】大模型基础知识(4)---ollama模型调用-多轮对话体验
python·ollama·大模型基础·ai 聊天机器人·简单的大模型部署·实现ollama模型调用·零基础上手 ollama体验
Apifox.18 小时前
测试用例越堆越多?用 Apifox 测试套件让自动化回归更易维护
运维·前端·后端·测试工具·单元测试·自动化·测试用例
AndrewHZ18 小时前
【Python与生活】怎么用python画出好看的分形图?
开发语言·python·生活·可视化·递归·分形
sunnyday042618 小时前
Nginx与Spring Cloud Gateway QPS统计全攻略
java·spring boot·后端·nginx