If your FastAPI endpoints fetch data through a get_db dependency, don’t test them against a real database — use TestClient together with app.dependency_overrides to swap that dependency for a fake repository. Tests run in milliseconds, need no running server, and your real data stays untouched.

The Problem

When writing tests for a database-backed API, the “naive” approach is to let the tests hit the real database. The problem: tests become slow and fragile — every machine running the tests needs a database running with the right configuration; tests are no longer independent because they depend on the state of the data; and worst of all, a wrong environment variable could make your tests overwrite production data.

A simple endpoint and a “naive” test that hits the real database:

from fastapi import Depends, FastAPI, HTTPException
from fastapi.testclient import TestClient
app = FastAPI()
class ItemRepo:
def get_item(self, item_id: int):
# production: query PostgreSQL here
...
def get_db():
repo = ItemRepo()
try:
yield repo
finally:
pass # close the real connection
@app.get("/items/{item_id}")
def read_item(item_id: int, db=Depends(get_db)):
item = db.get_item(item_id)
if item is None:
raise HTTPException(status_code=404, detail="Item not found")
return item
client = TestClient(app)
def test_read_item():
response = client.get("/items/1")
assert response.status_code == 200 # BREAKS if no real DB is running!

This test only passes when a real PostgreSQL instance is running with the right data — put it on CI and you have to spin up a database service, which is slow and flaky.

The Solution

FastAPI lets you override any dependency at test time through app.dependency_overrides — a dict mapping the original dependency to a replacement function. Write a fake repo that returns hardcoded data, then swap it in for get_db:

# pip install httpx (TestClient needs httpx)
from fastapi.testclient import TestClient
from main import app, get_db # main.py holds the endpoint code above
class FakeItemRepo:
"""Fake repo: returns hardcoded data, never touches the database."""
def __init__(self):
self._data = {1: {"id": 1, "name": "Keyboard"}}
def get_item(self, item_id: int):
return self._data.get(item_id)
def override_get_db():
yield FakeItemRepo()
# Swap the dependency — effective only in this test process
app.dependency_overrides[get_db] = override_get_db
client = TestClient(app)
def test_read_item_ok():
r = client.get("/items/1")
assert r.status_code == 200
assert r.json() == {"id": 1, "name": "Keyboard"}
def test_read_item_not_found():
r = client.get("/items/999")
assert r.status_code == 404

Why is this better? First, TestClient calls the app directly in the same Python process — no uvicorn, no network ports. Second, the override only lives in the test process; the production code doesn’t change by a single line. Third, tests become deterministic: the fake data is fully under your control, so they pass identically anywhere. With pytest, put the override in a fixture and call app.dependency_overrides.clear() in teardown so tests don’t leak into each other.

Apply It to Your Project

Apply this pattern to your first test module right away: separate data-access logic into a repo class (or its own dependency), then in tests write the matching fake class. Once you’re comfortable, you can override a cache dependency (Redis), third-party API clients, or the “clock” that returns the current time — they all use the same dependency_overrides mechanism. Put this suite on CI (GitHub Actions only needs to run pytest, no database service) and you have an automated, fast, reliable API test pipeline.

Related Posts

Frequently Asked Questions

Does TestClient need uvicorn running?

No. TestClient calls the ASGI application directly in the same Python process without opening network ports, so tests are fast and there are no port conflicts.

Does dependency_overrides change the app in production?

No. The override only applies in the test process that set it. When deployed, app.dependency_overrides is an empty dict, so the app uses the original dependencies. Remember to call clear() after each test so tests don’t affect each other.

How is a fake repo different from testing with in-memory SQLite?

In-memory SQLite is closer to reality (it runs real SQL queries) but is slower and requires schema setup. A fake repo is the fastest option and suits unit tests of endpoint logic. Larger projects usually use both: fakes for fast daily tests, SQLite for integration tests before merging.

What do I need to install to use TestClient?

Just pip install httpx — FastAPI’s TestClient (inherited from Starlette) uses httpx to simulate HTTP requests.

References