Introduction
When working with FastAPI, one of the most powerful features is its support for dependency injection. This not only boosts clean architecture but also makes testing much easier. In this guide, we’ll walk through how to achieve FastAPI unit testing with dependency overrides, making your tests faster, cleaner, and more reliable. If you’re looking for clean testing practices in FastAPI, this post is for you.
Why dependency overrides matter
FastAPI uses Python’s Depends system to inject dependencies into your route functions. This is helpful for things like:
- Connecting to databases
- Performing authentication
- Logging
However, when you’re writing unit tests, you often don’t want these real systems to run. Instead, you would prefer mocked or fake versions to isolate what you’re testing. This is the core idea behind testing FastAPI endpoints with mock dependencies.
A sample FastAPI app
Let’s start with a minimal FastAPI app using a simple dependency:
# app/main.py
from fastapi import FastAPI, Depends
app = FastAPI()
def get_data_source():
return {"message": "Hello from real source"}
@app.get("/data")
def read_data(data_source = Depends(get_data_source)):
return data_source
FastAPI unit testing with dependency overrides in action
Now let’s write a unit test that overrides the get_data_source dependency with a mock version.
# tests/test_main.py
from fastapi.testclient import TestClient
from app.main import app, get_data_source
def override_data_source():
return {"message": "Hello from mock"}
app.dependency_overrides[get_data_source] = override_data_source
client = TestClient(app)
def test_read_data():
response = client.get("/data")
assert response.status_code == 200
assert response.json() == {"message": "Hello from mock"}
What’s Happening?
- app.dependency_overrides[…] = …: This tells FastAPI to use override_data_sourceinstead ofget_data_source during this test.
- We use TestClient to simulate a call to the /data endpoint.
This demonstrates how to write unit tests in FastAPI using dependency overrides without relying on the actual implementation logic.
Resetting overrides (Best practice)
It’s a good idea to reset overrides after the test, especially if you’re running multiple tests. You can do this cleanly using pytest fixtures:
import pytest
from app.main import app
@pytest.fixture
def client():
from app.main import get_data_source
def override_data_source():
return {"message": "Hello from mock"}
app.dependency_overrides[get_data_source] = override_data_source
yield TestClient(app)
app.dependency_overrides = {}
Then your test:
def test_read_data(client):
response = client.get("/data")
assert response.json() == {"message": "Hello from mock"}
Real-world example: FastAPI dependency injection testing with a DB session
FastAPI is often used with SQLAlchemy. You can override the database session like this:
# Dependency in your app
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
In your test:
def override_get_db():
db = TestingSessionLocal()
try:
yield db
finally:
db.close()
app.dependency_overrides[get_db] = override_get_db
This example showcases FastAPI dependency injection testing and allows you to test against a temporary or mocked database—without touching production.
Asynchronous API testing in FastAPI
Many FastAPI endpoints are asynchronous (async def). Testing them is slightly different but equally supported.
If you have an async route like this:
@app.get("/async-data")
async def get_async_data():
return {"status": "async success"}
You can still use TestClient synchronously:
def test_get_async_data():
response = client.get("/async-data")
assert response.status_code == 200
assert response.json() == {"status": "async success"}
If you want to test the async logic in isolation, use pytest-asyncio like this:
import pytest
@pytest.mark.asyncio
async def test_some_async_function():
result = await some_async_logic()
assert result == expected_value
You can read more here about asynchronous API testing in FastAPI for deeper examples using httpx. AsyncClient and pytest-asyncio.
Conclusion
FastAPI’s dependency_overrides feature is an excellent tool for writing fast, isolated, and maintainable tests. Whether you’re testing endpoints, injecting mocked services, or validating output, the strategy fits right into FastAPI unit testing best practices.
If you’re aiming for scalable, test-driven development, understanding unit testing in FastAPI with dependency overrides is a key step. Start small, use mock services wisely, and your test suite will grow with confidence.