FastAPI

Lesson 09

Testing with dependency overrides

Override dependencies in tests instead of calling external services or patching internals.

Good Code

tests/test_reviews.py
from fastapi.testclient import TestClient

from app.main import app
from app.auth import current_user


def fake_current_user():
    return {"id": 1, "role": "reviewer"}


def test_approve_review():
    app.dependency_overrides[current_user] = fake_current_user
    client = TestClient(app)

    response = client.post("/reviews/10/approve")

    app.dependency_overrides = {}
    assert response.status_code == 200

Bad Code

tests/test_reviews.py
from fastapi.testclient import TestClient

from app.main import app

client = TestClient(app)


def test_approve_review():
    response = client.post(
        "/reviews/10/approve",
        headers={"Authorization": "Bearer production-token"},
    )

    assert response.status_code == 200

Review Notes

What to review

Good Code

The good version replaces the auth dependency with a test implementation and resets overrides after the assertion.

Bad Code

The bad version depends on a production-like token and whatever auth service is behind it. Tests become slow, flaky, and hard to reason about.

Takeaways

  • FastAPI dependency overrides make integration-style API tests fast and focused.