Overriding Dependencies

Fake Dependencies in Tests

Example

app.dependency_overrides swaps a real dependency (database, current user, external API) for a fake one in tests:

from typing import Annotated
from fastapi import Depends, FastAPI

app = FastAPI()

def get_current_user():
    raise RuntimeError("would call the real auth service")

@app.get("/dashboard")
def dashboard(user: Annotated[dict, Depends(get_current_user)]):
    return {"welcome": user["name"]}

# ---- in the test ----
app.dependency_overrides[get_current_user] = lambda: {"name": "Test User"}

Requests and responses

GET /dashboard
→ 200 {"welcome": "Test User"}

Tip: Clear overrides after each test (app.dependency_overrides.clear()), for example in a pytest fixture.