unit-testing
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseUnit Testing
单元测试
Test isolated business logic with fast, deterministic tests.
使用快速、可预测的测试来测试独立的业务逻辑。
AAA Pattern (Arrange-Act-Assert)
AAA模式(准备-执行-断言)
typescript
describe('calculateDiscount', () => {
test('applies 10% discount for orders over $100', () => {
// Arrange
const order = { items: [{ price: 150 }] };
// Act
const result = calculateDiscount(order);
// Assert
expect(result).toBe(15);
});
});typescript
describe('calculateDiscount', () => {
test('applies 10% discount for orders over $100', () => {
// Arrange
const order = { items: [{ price: 150 }] };
// Act
const result = calculateDiscount(order);
// Assert
expect(result).toBe(15);
});
});Test Isolation
测试隔离
typescript
describe('UserService', () => {
let service: UserService;
let mockRepo: MockRepository;
beforeEach(() => {
// Fresh instances per test
mockRepo = createMockRepository();
service = new UserService(mockRepo);
});
afterEach(() => {
// Clean up
vi.clearAllMocks();
});
});typescript
describe('UserService', () => {
let service: UserService;
let mockRepo: MockRepository;
beforeEach(() => {
// Fresh instances per test
mockRepo = createMockRepository();
service = new UserService(mockRepo);
});
afterEach(() => {
// Clean up
vi.clearAllMocks();
});
});Coverage Targets
覆盖率目标
| Area | Target |
|---|---|
| Business logic | 90%+ |
| Critical paths | 100% |
| New features | 100% |
| Utilities | 80%+ |
| 领域 | 目标 |
|---|---|
| 业务逻辑 | 90%+ |
| 关键路径 | 100% |
| 新功能 | 100% |
| 工具类 | 80%+ |
Parameterized Tests
参数化测试
typescript
describe('isValidEmail', () => {
test.each([
['test@example.com', true],
['invalid', false],
['@missing.com', false],
['user@domain.co.uk', true],
])('isValidEmail(%s) returns %s', (email, expected) => {
expect(isValidEmail(email)).toBe(expected);
});
});typescript
describe('isValidEmail', () => {
test.each([
['test@example.com', true],
['invalid', false],
['@missing.com', false],
['user@domain.co.uk', true],
])('isValidEmail(%s) returns %s', (email, expected) => {
expect(isValidEmail(email)).toBe(expected);
});
});Python Example
Python示例
python
import pytest
class TestCalculateDiscount:
def test_applies_discount_over_threshold(self):
# Arrange
order = Order(total=150)
# Act
discount = calculate_discount(order)
# Assert
assert discount == 15
@pytest.mark.parametrize("total,expected", [
(100, 0),
(101, 10.1),
(200, 20),
])
def test_discount_thresholds(self, total, expected):
order = Order(total=total)
assert calculate_discount(order) == expectedpython
import pytest
class TestCalculateDiscount:
def test_applies_discount_over_threshold(self):
# Arrange
order = Order(total=150)
# Act
discount = calculate_discount(order)
# Assert
assert discount == 15
@pytest.mark.parametrize("total,expected", [
(100, 0),
(101, 10.1),
(200, 20),
])
def test_discount_thresholds(self, total, expected):
order = Order(total=total)
assert calculate_discount(order) == expectedFixture Scoping (2026 Best Practice)
Fixture作用域(2026最佳实践)
python
import pytestpython
import pytestFunction scope (default): Fresh instance per test - ISOLATED
Function scope (default): Fresh instance per test - ISOLATED
@pytest.fixture(scope="function")
def db_session():
"""Each test gets clean database state."""
session = create_session()
yield session
session.rollback() # Cleanup
@pytest.fixture(scope="function")
def db_session():
"""Each test gets clean database state."""
session = create_session()
yield session
session.rollback() # Cleanup
Module scope: Shared across all tests in file - EFFICIENT
Module scope: Shared across all tests in file - EFFICIENT
@pytest.fixture(scope="module")
def expensive_model():
"""Load once per test file (expensive setup)."""
return load_large_ml_model() # 5 seconds to load
@pytest.fixture(scope="module")
def expensive_model():
"""Load once per test file (expensive setup)."""
return load_large_ml_model() # 5 seconds to load
Session scope: Shared across ALL tests - MOST EFFICIENT
Session scope: Shared across ALL tests - MOST EFFICIENT
@pytest.fixture(scope="session")
def db_engine():
"""Single connection pool for entire test run."""
engine = create_engine(TEST_DB_URL)
Base.metadata.create_all(engine)
yield engine
Base.metadata.drop_all(engine)
**When to use each scope:**
| Scope | Use Case | Example |
|-------|----------|---------|
| function | Isolated tests, mutable state | db_session, mock objects |
| module | Expensive setup, read-only | ML model, compiled regex |
| session | Very expensive, immutable | DB engine, external service |@pytest.fixture(scope="session")
def db_engine():
"""Single connection pool for entire test run."""
engine = create_engine(TEST_DB_URL)
Base.metadata.create_all(engine)
yield engine
Base.metadata.drop_all(engine)
**何时使用各作用域:**
| 作用域 | 使用场景 | 示例 |
|-------|----------|---------|
| function | 独立测试、可变状态 | db_session、模拟对象 |
| module | 高成本初始化、只读 | ML模型、编译后的正则表达式 |
| session | 极高成本初始化、不可变 | 数据库引擎、外部服务 |Indirect Parametrization
间接参数化
python
undefinedpython
undefinedDefer expensive setup from collection to runtime
Defer expensive setup from collection to runtime
@pytest.fixture
def user(request):
"""Create user with different roles based on parameter."""
role = request.param # Receives value from parametrize
return UserFactory(role=role)
@pytest.mark.parametrize("user", ["admin", "moderator", "viewer"], indirect=True)
def test_permissions(user):
"""Test runs 3 times with different user roles."""
# user fixture is called with each role
assert user.can_access("/dashboard") == (user.role in ["admin", "moderator"])
@pytest.fixture
def user(request):
"""Create user with different roles based on parameter."""
role = request.param # Receives value from parametrize
return UserFactory(role=role)
@pytest.mark.parametrize("user", ["admin", "moderator", "viewer"], indirect=True)
def test_permissions(user):
"""Test runs 3 times with different user roles."""
# user fixture is called with each role
assert user.can_access("/dashboard") == (user.role in ["admin", "moderator"])
Combinatorial testing with stacked decorators
Combinatorial testing with stacked decorators
@pytest.mark.parametrize("role", ["admin", "user"])
@pytest.mark.parametrize("status", ["active", "suspended"])
def test_access_matrix(role, status):
"""Runs 4 tests: admin/active, admin/suspended, user/active, user/suspended"""
user = User(role=role, status=status)
expected = (role == "admin" and status == "active")
assert user.can_modify() == expected
undefined@pytest.mark.parametrize("role", ["admin", "user"])
@pytest.mark.parametrize("status", ["active", "suspended"])
def test_access_matrix(role, status):
"""Runs 4 tests: admin/active, admin/suspended, user/active, user/suspended"""
user = User(role=role, status=status)
expected = (role == "admin" and status == "active")
assert user.can_modify() == expected
undefinedKey Decisions
关键决策
| Decision | Recommendation |
|---|---|
| Framework | Vitest (modern), Jest (mature), pytest |
| Execution | < 100ms per test |
| Dependencies | None (mock everything external) |
| Coverage tool | c8, nyc, pytest-cov |
| 决策 | 推荐方案 |
|---|---|
| 框架 | Vitest(现代)、Jest(成熟)、pytest |
| 执行时间 | 每个测试<100ms |
| 依赖 | 无(模拟所有外部依赖) |
| 覆盖率工具 | c8、nyc、pytest-cov |
Common Mistakes
常见错误
- Testing implementation, not behavior
- Slow tests (external calls)
- Shared state between tests
- Over-mocking (testing mocks not code)
- 测试实现细节而非行为
- 测试速度慢(包含外部调用)
- 测试间共享状态
- 过度模拟(测试模拟对象而非实际代码)
Related Skills
相关技能
- - Testing interactions
integration-testing - - Network mocking
msw-mocking - - Fixtures and factories
test-data-management
- - 测试交互逻辑
integration-testing - - 网络模拟
msw-mocking - - 测试数据与工厂类
test-data-management
Capability Details
能力细节
pytest-patterns
pytest-patterns
Keywords: pytest, python, fixture, parametrize
Solves:
- Write pytest unit tests
- Use fixtures effectively
- Parametrize test cases
关键词: pytest、python、fixture、parametrize
解决问题:
- 编写pytest单元测试
- 高效使用fixture
- 参数化测试用例
vitest-patterns
vitest-patterns
Keywords: vitest, jest, typescript, mock
Solves:
- Write Vitest unit tests
- Mock dependencies
- Test React components
关键词: vitest、jest、typescript、mock
解决问题:
- 编写Vitest单元测试
- 模拟依赖项
- 测试React组件
orchestkit-strategy
orchestkit-strategy
Keywords: orchestkit, strategy, coverage, pyramid
Solves:
- OrchestKit test strategy example
- Test coverage targets
- Testing pyramid ratios
关键词: orchestkit、strategy、coverage、pyramid
解决问题:
- OrchestKit测试策略示例
- 测试覆盖率目标
- 测试金字塔比例
test-case-template
test-case-template
Keywords: template, test, structure, arrange
Solves:
- Test case template
- Arrange-Act-Assert structure
- Copy-paste test starter
关键词: template、test、structure、arrange
解决问题:
- 测试用例模板
- 准备-执行-断言结构
- 可复制的测试起始模板