FastAPI dependency override not applied in tests in CI
FastAPI replaces a dependency only when the override dictionary key is the exact same callable passed to Depends. If the key is a different function object, the override is silently ignored and the real dependency runs, which in CI often means a missing database or service.
What this error means
A test that sets app.dependency_overrides[get_db] = ... still runs the real dependency: you see a connection error or the production code path, and the override appears to have no effect.
# override set, yet the real get_db still runs:
sqlalchemy.exc.OperationalError: (psycopg.OperationalError) connection to
server at "localhost" (127.0.0.1), port 5432 failed: Connection refusedCommon causes
The override key is not the exact Depends callable
The key is a re-imported or wrapped copy of the dependency, not the identical object used in Depends(...), so FastAPI never matches it.
The override was set on a different app instance
Tests build their own app or import a different module, so overrides are attached to an app the client does not use.
How to fix it
Override the exact callable on the same app
- Import the identical dependency function used in the routes.
- Set the override on the same
appthe TestClient wraps. - Clear overrides in teardown to avoid leaking between tests.
from app.main import app
from app.deps import get_db
def override_get_db():
yield test_session
app.dependency_overrides[get_db] = override_get_db
# in teardown:
app.dependency_overrides.clear()Confirm the client uses the overridden app
Construct the TestClient from the same app object that holds the overrides.
from fastapi.testclient import TestClient
client = TestClient(app)How to prevent it
- Use the exact dependency callable as the override key.
- Attach overrides to the same app instance the client uses.
- Clear
dependency_overridesin fixture teardown.