The Problem: Testing with Real Dependencies
Consider an application that depends on a database:- Slow: Real database connections take time
- Fragile: Tests fail if the database is unavailable
- Dangerous: Tests might modify production data
Solution: Dependency Overrides
Useapp.dependency_overrides to replace dependencies during testing:
The override maps the original dependency function to the replacement function. FastAPI will call the replacement whenever the original is used.
How It Works
FastAPI’s dependency resolution system checksapp.dependency_overrides before calling any dependency. The implementation is in fastapi/dependencies/utils.py:629-644:
- Dependency resolution begins
- For each dependency, check if an override exists
- If yes, use the override; if no, use the original
- Cache and resolve the dependency normally
Overrides work for dependencies used anywhere: path operation parameters, nested dependencies, and decorator-level dependencies.
Basic Usage Patterns
Overriding a Simple Dependency
Overriding with Different Parameters
The override dependency can have completely different parameters:Advanced Override Patterns
Overriding Generator Dependencies
Generator dependencies withyield can be overridden:
You can override a generator dependency with a regular function, and vice versa. FastAPI handles both correctly.
Overriding Nested Dependencies
When dependencies depend on other dependencies, you can override at any level:Overriding Router Dependencies
Dependencies in routers are also overridable:Overriding with Async Dependencies
Async dependencies can override sync dependencies and vice versa:FastAPI automatically handles async/sync conversions when resolving overrides.
Testing Patterns
Using Pytest Fixtures
Create reusable override fixtures:Context Manager for Overrides
Create a context manager for temporary overrides:Testing Multiple Overrides
Common Patterns
Mocking External APIs
Testing Authentication
Testing with Stateful Mocks
Best Practices
Type hints still apply: Even though you’re overriding dependencies, FastAPI still validates and converts parameters based on type hints.
See Also
- Testing - General testing guide
- Advanced Dependencies - Advanced dependency patterns
- Testing Dependencies with Overrides - FastAPI docs