← Back to FastAPI, page 4

fastapi-0070 · Medium mid

How do you replace dependencies such as the database, current user or external clients in FastAPI tests with app.dependency_overrides?

app.dependency_overrides is a dict mapping an original dependency callable to a replacement. Inside a test, set overrides[get_db] = fake_get_db (and clear it afterwards) so endpoints use test doubles without patching modules. Overrides apply to the whole dependency tree, including sub-dependencies, are keyed by the exact function object, and should be reset with a fixture so tests stay independent.

Full answer

Because FastAPI resolves Depends(get_current_user) at request time, tests can swap what runs without touching endpoint code:

python
def override_user():
    return User(id=1, role="admin")

app.dependency_overrides[get_current_user] = override_user
...
app.dependency_overrides.clear()

Key points:

  • The key must be the same function object used in Depends(...). Overriding a function re-imported under another name does nothing.
  • The replacement may have its own dependencies and its own signature (parameters are resolved normally), including yield for setup and teardown.
  • Typical overrides: database session (test database or transaction), authenticated user (skip real login), settings (get_settings), outbound clients (fake payment gateway), time or ID generators.
  • In pytest, wrap in a fixture so cleanup always happens:
python
@pytest.fixture
def client():
    app.dependency_overrides[get_db] = override_get_db
    with TestClient(app) as c:
        yield c
    app.dependency_overrides.clear()
  • Overrides replace the dependency but not its decorators (like lru_cache on get_settings; clear caches if needed), and router-level dependencies=[Depends(x)] are overridden the same way.
  • Security dependencies (OAuth2PasswordBearer) can be overridden to bypass tokens: override the dependency that returns the user, and keep a few tests that go through real authentication.
  • For parallel test runs, remember dependency_overrides is global to the app object; create the app with a factory (create_app()) per test or process.

Alternatives: unittest.mock.patch works but couples tests to import paths; dependency overrides are the supported mechanism and keep tests independent of how modules are laid out.

python
from typing import Annotated

from fastapi import Depends, FastAPI, HTTPException
from fastapi.testclient import TestClient

app = FastAPI()


class RealMailer:
    def send(self, to, text):
        raise RuntimeError("real SMTP must not be called in tests")


def get_mailer():
    return RealMailer()


def get_current_user() -> dict:
    raise HTTPException(status_code=401, detail="Not authenticated")


@app.post("/receipts/{roll_no}")
def send_receipt(roll_no: str, user: Annotated[dict, Depends(get_current_user)],
                 mailer: Annotated[RealMailer, Depends(get_mailer)]):
    mailer.send(f"{roll_no}@example.com", "fee received")
    return {"sent_by": user["name"], "to": roll_no}


class FakeMailer:
    def __init__(self):
        self.outbox = []

    def send(self, to, text):
        self.outbox.append((to, text))


c = TestClient(app)
print("no override:", c.post("/receipts/BCA-1").status_code)

fake = FakeMailer()
app.dependency_overrides[get_current_user] = lambda: {"name": "teacher"}
app.dependency_overrides[get_mailer] = lambda: fake
print(c.post("/receipts/BCA-1").json(), fake.outbox)

app.dependency_overrides.clear()
print("after clear:", c.post("/receipts/BCA-1").status_code)

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): no override: 401 {'sent_by': 'teacher', 'to': 'BCA-1'} [('BCA-1@example.com', 'fee received')] after clear: 401

Key points

  • dependency_overrides maps original dependency to replacement
  • Key must be the exact function used in Depends
  • Replacement can have its own dependencies and yield
  • Use a fixture to clear overrides after each test
  • Keep a few tests that use real authentication

Common mistakes

  • Forgetting to clear overrides, leaking state into other tests
  • Overriding a function object that is not the one used in Depends
  • Overriding authentication everywhere and never testing the real login path
  • Sharing one app object across parallel tests with different overrides

Follow-ups

  • How do you test a dependency that uses yield?
  • How do you override a router-level dependency?
  • Why prefer overrides to mock.patch?

Tips

  • Show the dict and the fixture
  • Say key equals function object
  • Mention tests with real auth