FastAPI: From Basics to Production · Testing FastAPI Applications

Dependency Overrides in Tests

Swap auth, settings and external services in tests.

app.dependency_overrides[original] = replacement replaces a dependency for tests: fake the current user, use test settings, or substitute external clients (payment gateway, email). Clear overrides after each test to avoid leaks. Prefer overriding at boundaries (auth, external services) and keeping real logic in between.

import pytest
from app.auth import get_current_user
from app.integrations import get_mailer
from app.main import app


class FakeMailer:
    def __init__(self):
        self.sent: list[tuple[str, str]] = []

    async def send(self, to: str, subject: str, body: str) -> None:
        self.sent.append((to, subject))


@pytest.fixture
def mailer():
    fake = FakeMailer()
    app.dependency_overrides[get_mailer] = lambda: fake
    app.dependency_overrides[get_current_user] = lambda: User(id=1, email="[email protected]", permissions={"orders:read"})
    yield fake
    app.dependency_overrides.clear()


def test_signup_sends_welcome_email(client, mailer):
    client.post("/signup", json={"email": "[email protected]", "password": "correct horse battery"})
    assert mailer.sent == [("[email protected]", "Welcome!")]

Common pitfalls

  • Forgetting to clear overrides, leaking into other tests.
  • Overriding so much that tests no longer exercise real behavior.
  • Overriding the wrong function object (must be the exact dependency callable).

Key points

  • dependency_overrides swaps dependencies
  • Fake external services and auth
  • Clear overrides after each test

Further reading: FastAPI: Testing dependencies with overrides

Practice questions

How do you test an endpoint that requires authentication without real tokens?

Answer

Override get_current_user with a function returning a test user via app.dependency_overrides.

Why must overrides be cleared after each test?

Answer

The overrides dict is global on the app; leftover overrides make other tests run with fakes unintentionally.

Open in the app to mark lessons complete, take notes and track your progress.