欢迎来到程序员中文网!

首页 Linux Mysql C++ Python PHP JavaScript 资源下载 动态 开源推荐
我要投稿 投诉建议

Python 单元测试 pytest 与 Mock 使用指南

时间:2026年08月12日 05:40:34 浏览:1

Python 单元测试 pytest 与 Mock 使用指南


pytest 是 Python 最流行的测试框架,简洁且功能强大。


1. 基本测试


def add(a, b):
return a + b

def test_add():
assert add(1, 2) == 3
assert add(-1, 1) == 0

运行 pytest 即可自动发现 test_*.py 文件。


2. 参数化测试


import pytest

@pytest.mark.parametrize('a,b,expected', [
(1, 2, 3),
(0, 0, 0),
(-1, 1, 0)
])
def test_add_param(a, b, expected):
assert add(a, b) == expected

3. 使用 Mock 模拟依赖


from unittest.mock import Mock

def test_user_service():
mock_db = Mock()
mock_db.get_user.return_value = {'id': 1, 'name': 'Alice'}
service = UserService(mock_db)
assert service.get_user_name(1) == 'Alice'

4. 夹具(Fixtures)


@pytest.fixture
def sample_data():
return {'name': 'test', 'value': 42}

def test_fixture(sample_data):
assert sample_data['value'] == 42

5. 覆盖率和报告


pytest --cov=. --cov-report=html

单元测试是代码质量的基石,pytest 是首选工具。