单元测试基础
编写 and 运行测试使用 unittest and pytest: assertions, fixtures, mocking, and coverage.
你将学到
- 编写测试情况使用 unittest.TestCase
- Use pytest for simpler, 更多 powerful 测试
- Apply assertions and 测试 discovery
- Use fixtures and parametrized 测试
- Measure and improve 测试 coverage
概念讲解
Why Test?
Tests verify that your code works correctly and catch regressions when you make changes. Without tests, every modification is a gamble — you might break something without knowing. Testing is a fundamental professional skill.
Benefits:
- Catch bugs early — before they reach production
- Refactor with confidence — tests verify behavior is preserved
- Documentation — tests show how the code is supposed to work
- Design aid — writing tests first (TDD) leads to better APIs
unittest — The Standard Library Framework
Python's built-in unittest module provides a testing framework:
import unittest
# The code we want to test
def add(a, b):
return a + b
def is_even(n):
return n % 2 == 0
# The test class
class TestMathFunctions(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)
self.assertEqual(add(-1, 1), 0)
self.assertEqual(add(0, 0), 0)
def test_is_even(self):
self.assertTrue(is_even(4))
self.assertFalse(is_even(3))
if __name__ == "__main__":
unittest.main()
Test methods must start with test_. The unittest.主要() call discovers and runs all tests. Run with python test_file.py.
Common Assertions
class TestExample(unittest.TestCase):
def test_assertions(self):
# Equality
self.assertEqual(2 + 2, 4)
self.assertNotEqual(2 + 2, 5)
# Truthiness
self.assertTrue(True)
self.assertFalse(False)
# None checks
self.assertIsNone(None)
self.assertIsNotNone(42)
# Containment
self.assertIn(3, [1, 2, 3])
self.assertNotIn(4, [1, 2, 3])
# Type checks
self.assertIsInstance("hello", str)
# Exceptions — assert code raises an error
with self.assertRaises(ZeroDivisionError):
result = 10 / 0
# Approximate equality for floats
self.assertAlmostEqual(0.1 + 0.2, 0.3, places=7)
setUp and tearDown
class TestDatabase(unittest.TestCase):
def setUp(self):
"""运行之前 EACH 测试方法."""
self.db = create_test_database()
self.db.connect()
def tearDown(self):
"""运行之后 EACH 测试方法."""
self.db.close()
def test_insert(self):
self.db.insert("用户", {"name": "Ada"})
self.assertEqual(self.db.count("用户"), 1)
def test_delete(self):
self.db.insert("用户", {"name": "Bob"})
self.db.delete("用户", "Bob")
self.assertEqual(self.db.count("用户"), 0)
设置 creates a fresh test environment before each test, and tearDown cleans up after. This ensures tests are isolated — they do not affect each other.
pytest — The Simpler, More Powerful Framework
pytest is the most popular third-party testing framework. It requires less boilerplate and has more features:
pip install pytest
# test_math.py — no classes needed!
def test_add():
assert add(2, 3) == 5
assert add(-1, 1) == 0
def test_is_even():
assert is_even(4) == True
assert is_even(3) == False
def test_divide_by_zero():
import pytest
with pytest.raises(ZeroDivisionError):
10 / 0
Run with pytest — it automatically discovers files named test_*.py and functions named test_*. The plain assert statement is the biggest advantage — no self.assertEqual boilerplate.
pytest Fixtures
Fixtures provide reusable setup logic:
import pytest
@pytest.fixture
def sample_list():
"""Provide fresh 列表 for 每个测试."""
return [1, 2, 3, 4, 5]
def test_sum(sample_list):
assert sum(sample_list) == 15
def test_length(sample_list):
assert len(sample_list) == 5
@pytest.fixture
def db_connection():
"""设置 and teardown 使用 yield."""
conn = create_connection()
yield conn # test runs here
conn.close() # cleanup
def test_query(db_connection):
assert db_connection.query("SELECT 1") == 1
Fixtures are injected by name — pytest sees sample_list in the function signature and calls the fixture. The yield form handles both setup (before yield) and teardown (after yield).
Parametrized Tests
Run the same test with multiple inputs:
import pytest
@pytest.mark.parametrize(", b, expected", [
(1, 2, 3),
(-1, 1, 0),
(0, 0, 0),
(100, 200, 300),
])
def test_add(a, b, expected):
assert add(a, b) == expected
@pytest.mark.parametrize("n, expected", [
(2, True),
(3, False),
(4, True),
(0, True),
])
def test_is_even(n, expected):
assert is_even(n) == expected
Parametrized tests eliminate duplication — one test function covers many cases, and each case appears separately in the test report.
Running Tests
# Run all tests
pytest
# Run a specific file
pytest test_math.py
# Run a specific test
pytest test_math.py::test_add
# Verbose output
pytest -v
# Stop on first failure
pytest -x
# Show print output
pytest -s
# Run only tests matching a pattern
pytest -k "添加"
Coverage
Measure how much of your code is tested:
pip install pytest-cov
pytest --cov=myapp --cov-report=term-missing
Coverage shows which lines are not tested. Aim for high coverage on critical paths, but remember: 100% coverage does not mean 100% correctness — you still need meaningful assertions.
Test Organization
project/
├── src/
│ └── myapp/
│ ├── calculator.py
│ └── parser.py
└── tests/
├── test_calculator.py
├── test_parser.py
└── conftest.py # shared fixtures
conftest.py contains shared fixtures available to all tests in the directory. Keep tests in a separate 测试/ directory, mirroring your source structure.
示例代码
import unittest
import pytest
# --- Code to test ---
def add(a, b):
return a + b
def is_even(n):
return n % 2 == 0
def factorial(n):
if n < 0:
raise ValueError("n must be non-negative")
if n <= 1:
return 1
result = 1
for i in range(2, n + 1):
result *= i
return result
# --- unittest style ---
class TestMath(unittest.TestCase):
def setUp(self):
self.test_data = [1, 2, 3, 4, 5]
def test_add(self):
self.assertEqual(add(2, 3), 5)
self.assertEqual(add(-1, 1), 0)
self.assertEqual(add(0, 0), 0)
def test_is_even(self):
self.assertTrue(is_even(4))
self.assertFalse(is_even(3))
self.assertTrue(is_even(0))
def test_factorial(self):
self.assertEqual(factorial(0), 1)
self.assertEqual(factorial(1), 1)
self.assertEqual(factorial(5), 120)
with self.assertRaises(ValueError):
factorial(-1)
# --- pytest style (simpler!) ---
def test_add():
assert add(2, 3) == 5
assert add(-1, 1) == 0
assert add(0, 0) == 0
def test_is_even():
assert is_even(4) is True
assert is_even(3) is False
@pytest.mark.parametrize("n, expected", [
(0, 1), (1, 1), (2, 2), (3, 6), (4, 24), (5, 120),
])
def test_factorial(n, expected):
assert factorial(n) == expected
def test_factorial_negative():
with pytest.raises(ValueError):
factorial(-1)
# --- pytest fixture ---
@pytest.fixture
def numbers():
return [1, 2, 3, 4, 5]
def test_sum(numbers):
assert sum(numbers) == 15
def test_max(numbers):
assert max(numbers) == 5
# Run: pytest test_file.py -v
# Run unittest: python -m unittest test_file.py
Shows 两者都 unittest (TestCase, 设置, assertions) and pytest (plain assert, fixtures, parametrize) 样式 for 测试添加, is_even, and factorial 函数. pytest 是 simpler and 更多 powerful.
动手试一试
- JSON Formatter
测试 JSON serialization/deserialization 是常见单元测试场景.
- Regex Tester
Regex 模式应该是 tested 使用各种输入 — parametrize 是 ideal.
常见错误
错误写法
编写测试那个 depend on 顺序 or shared 可变状态
正确做法
每个测试应该是 independent — 它应该不 rely on other 测试运行首先 or 修改 shared 状态. Use 设置/tearDown or pytest fixtures 到创建 fresh 环境 for 每个测试. 测试那个 depend on 顺序是 fragile and 困难到 调试.
错误写法
测试 implementation details 相反的 behavior
正确做法
测试什么函数做 (它的 observable behavior), 不如何它 做它 (内部 implementation). 测试那个检查私有方法 or 内部状态 break 当你 refactor. Focus on 输入 and 输出 — 如果函数返回正确 result for 各种输入, 它工作正确地.
相关资源
相关速查表
- Python Cheatsheet
unittest and pytest 语法, assertions, and fixtures.
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。