Lesson 9 / 26
Testing With Dependency Overrides
Swap real resources for test doubles.
app.dependency_overrides
FastAPI tests use TestClient (or httpx's AsyncClient for async tests) with pytest. Because resources come from dependencies, tests replace them through app.dependency_overrides[real] = fake: a fake database, a stub payment client, a fixed current user. This keeps tests fast and isolated without patching internals. Clear overrides after each test, and add a few integration tests against a real database.
Overriding a database dependency, run
I ran this with Python 3.12, FastAPI 0.142.2, Pydantic 2.13 and Starlette 1.7, calling the app through FastAPI's TestClient (no server needed). The real get_db would fail, but the override supplies an in-memory dict with two products, so the endpoint returns a count of 2.
from typing import Annotated
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
def get_db():
raise RuntimeError("would connect to the real database")
app = FastAPI()
@app.get("/count")
def count(db: Annotated[dict, Depends(get_db)]):
return {"products": len(db["products"])}
app.dependency_overrides[get_db] = lambda: {"products": ["pen", "ink"]} # test double
client = TestClient(app)
print(client.get("/count").json())
Output:
{'products': 2}Reset overrides between tests
Use a pytest fixture that sets overrides and clears app.dependency_overrides afterwards.
Quick check: How do you replace a database dependency in a FastAPI test?
- Disable Pydantic
- Edit the source file during the test
- Set app.dependency_overrides[get_db] to a fake
- Restart uvicorn
Answer
Set app.dependency_overrides[get_db] to a fake — Dependencies make testing easy.