1.基础用法
1 | from fastapi import Depends, FastAPI |
- 通过
dependency_overrides字典动态替换依赖项实现 - 测试流程:
graph TD A[初始化TestClient] --> B[覆盖依赖项] B --> C[发送模拟请求] C --> D[验证响应参数] D --> E[对比覆盖后的参数]
2.进阶配置
2.1 多依赖项覆盖
1 | # 覆盖多个依赖项 |
- 使用
update()方法批量覆盖多个依赖项 - 适用场景:同时测试业务逻辑和数据库交互
2.2 子依赖项测试
1 | async def sub_dependency(): |
- 支持覆盖依赖链中的任意层级
- 可实现精准的单元测试隔离
3.生产环境建议
数据库测试:
1
2
3
4def override_db():
test_engine = create_engine("sqlite:///./test.db")
return Session(test_engine)
app.dependency_overrides[get_db] = override_db使用内存数据库或专用测试数据库
认证模拟:
1
2
3def bypass_auth():
return User(id=1, is_admin=False)
app.dependency_overrides[get_current_user] = bypass_auth绕过OAuth2等复杂认证流程
错误处理:
1
2
3def force_error():
raise HTTPException(500)
app.dependency_overrides[safe_dependency] = force_error测试异常处理逻辑的健壮性
性能监控:
- 使用
pytest-benchmark测量依赖项执行时间 - 建议单个依赖项执行时间<50ms
- 使用
测试命令示例:
1
2
3
4
5 # 运行所有测试
pytest test_dependencies.py -v
# 生成测试覆盖率报告
pytest --cov=app --cov-report=html