如何编写Python单元测试?`unittest` 和 `pytest` 有什么…
中等Python
问题
如何编写Python单元测试?unittest 和 pytest 有什么区别?
答题要点
- unittest: 标准库,Java JUnit风格(类组织)。
- pytest: 第三方库(推荐),函数式风格,assert更简单,插件丰富。
# pytest 示例
def add(x, y):
return x + y
# 测试函数
def test_add():
assert add(1, 2) == 3
assert add(-1, 1) == 0
# Fixtures (准备数据)
import pytest
@pytest.fixture
def sample_data():
return {"a": 1}
def test_data(sample_data):
assert sample_data['a'] == 1
完整解析在题库里看
核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。
去练这道题