Tech Verse Logo
Enable dark mode
FastAPI Dependency Overrides for Integration Testing

FastAPI Dependency Overrides for Integration Testing

•4 min read

FastAPI integration tests use the app.dependency_overrides dictionary to swap production dependencies for test doubles. By mapping original functions to mock providers and clearing the dictionary afterward, you prevent test state leakage and keep your automated test suites fast and reliable.

Writing integration tests for web APIs often brings a specific kind of pain. You want to test the routing, validation, and serialization logic without hitting external services or leaking database state between test runs. If you have built systems that suffer from state leakage issues, you know how important it is to handle scope management correctly, as detailed in our guide on handling dependency scopes safely. FastAPI makes this surprisingly straightforward through app-level and router-level dependency overrides, but you'll have to set up your fixtures correctly to avoid flaky tests.

Most developers start testing by writing custom test clients that instantiate the application directly. That works until your endpoints require a database session or an active user context from an identity provider. Mocking these dependencies globally ruins parallel test execution. You need a clean way to swap out concrete implementations for test doubles during execution.

Setting Up the Application Structure

To understand how overrides work, you need a standard application layout with distinct dependency providers. Let's look at a minimal FastAPI app that injects a database session and a current user into its path operations. We'll keep the code explicit so the override mechanism is obvious.


from fastapi import Depends, FastAPI, HTTPException, status
from sqlalchemy.orm import Session

app = FastAPI()

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

def get_current_user(token: str = "default"): 
    if token != "secret-token":
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials")
    return {"id": 1, "username": "admin"}

@app.get("/profile")
def read_profile(db: Session = Depends(get_db), current_user: dict = Depends(get_current_user)):
    return {"user": current_user, "database_connected": True}

In this setup, hitting /profile requires both a valid database session generator and a matching token string. If you write an integration test using TestClient right now, it'll attempt to open a real database connection and validate real tokens. That's not what you want in a fast CI pipeline. You need to swap get_db and get_current_user on the fly. It's a common requirement when scaling up backend architectures.

You can't rely on global state when you're writing automated tests. It doesn't scale. If test A modifies the global application instance and test B runs concurrently, you'll see intermittent failures that take hours to trace. FastAPI's override dictionary avoids this architectural trap by scoping changes cleanly to the app instance you provide.

Writing the Test Suite with Overrides

FastAPI applications expose an app.dependency_overrides dictionary. This dictionary maps original dependency callables to their replacement functions or generators. You can mutate this dictionary inside your test setup and clear it afterward. When writing your test suite, you might also want to explore writing clean pytest fixtures to keep your test files readable and maintainable.

Here's how you configure a test file using pytest and FastAPI's built-in TestClient to replace both the database session and the authentication dependency.


from fastapi.testclient import TestClient
import pytest

from main import app, get_current_user, get_db

class MockSession:
    def __init__(self):
        self.closed = False

    def close(self):
        self.closed = True

def override_get_db():
    db = MockSession()
    try:
        yield db
    finally:
        db.close()

def override_get_current_user():
    return {"id": 99, "username": "test_user"}

app.dependency_overrides[get_db] = override_get_db
app.dependency_overrides[get_current_user] = override_get_current_user

client = TestClient(app)

def test_read_profile():
    response = client.get("/profile")
    assert response.status_code == 200
    assert response.json() == {
        "user": {"id": 99, "username": "test_user"},
        "database_connected": True
    }

def teardown_module(module):
    app.dependency_overrides.clear()

The important detail here is the cleanup step. If you don't clear app.dependency_overrides after your test module finishes executing, those mocks will persist into subsequent test files. That leads to strange failures where database endpoints suddenly return mock data during unrelated tests. Always clear the dictionary in a teardown hook or a fixture cleanup scope. Don't skip this. It'll save you from phantom bugs in your CI builds.

Sometimes you need to inspect how the dependency behaves under failure conditions. You can update the override mid-test to raise exceptions or return invalid payloads. This flexibility makes FastAPI testing much more powerful than traditional framework approaches where dependency containers are locked down tightly at boot time.

Handling Database Transactions Per Test

Mocking the database session with a dummy object works for simple smoke tests, but integration tests often need to verify that data actually gets written and queried correctly. For real database integration testing, you should point your application to an ephemeral SQLite database or a dedicated test PostgreSQL instance, wrapping each test function in a rollback transaction.

You achieve this by overriding the database dependency inside a pytest fixture that yields a rollback-enabled session. This ensures that any rows inserted during a test are wiped out immediately afterward, keeping your test suite deterministic without requiring manual table truncation. It's fast, and it avoids dirty state accumulation.

Let's look at how a transaction-scoped fixture looks in practice. You'll want to bind it to a session factory that points directly to your test database URL.


import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from main import app, get_db

TEST_DATABASE_URL = "sqlite:///:memory:"

engine = create_engine(TEST_DATABASE_URL, connect_args={"check_same_thread": False})
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

@pytest.fixture(autouse=True)
def db_override():
    connection = engine.connect()
    transaction = connection.begin()
    session = TestingSessionLocal(bind=connection)
    
    def override_get_db():
        try:
            yield session
        finally:
            session.close()
            
    app.dependency_overrides[get_db] = override_get_db
    yield
    transaction.rollback()
    connection.close()
    app.dependency_overrides.clear()

This pattern gives you the best of both worlds. You're hitting a real SQL engine, so your SQLAlchemy models, constraints, and relationships are fully exercised. At the same time, the rollback guarantees that every test starts with a completely pristine database state. You don't have to delete records manually or write complex teardown queries.

It's worth noting that if your application uses async database drivers like asyncpg, you'll need an async-compatible fixture setup using pytest-asyncio. The logic remains identical, but you'll yield an async session instead. Don't mix sync and async session makers blindly, or you'll trigger runtime greenlet errors that are painful to debug.

WRITTEN BY

Full Stack Software Engineer | Laravel · Next.js · AWS

Full Stack Software Engineer with 7+ years of experience building scalable, secure web applications with Laravel, PHP, React, Next.js, and AWS for SaaS, CRM, telecom, and e-commerce companies. Specialized in cloud telephony (FreeSWITCH, SMPP, WebRTC): increased concurrent call capacity by 40% and cut report queries to under 500 ms. Author of open-source Laravel packages with 10K+ downloads on Packagist. Led a team of 4 engineers and shipped production systems for clients in the UAE, USA, India, Saudi Arabia, and Bangladesh.

Reviewed by Md. Mostafijur Rahman on . How we research, write and check articles

    Latest Posts

    View All

    Next.js Middleware Authentication and Token Refresh Flows

    Next.js Middleware Authentication and Token Refresh Flows

    Livewire Performance Optimization Under High Load

    Livewire Performance Optimization Under High Load

    Configuring Nginx Upstream Keepalive for Node Backends

    Configuring Nginx Upstream Keepalive for Node Backends

    Enforcing Immutable State Patterns in React

    Enforcing Immutable State Patterns in React

    FastAPI Dependency Overrides for Integration Testing

    FastAPI Dependency Overrides for Integration Testing

    Stopping Layout Shifts in Next.js Dynamic Imports

    Stopping Layout Shifts in Next.js Dynamic Imports

    Optimizing Agentic Tool Calling Latency

    Optimizing Agentic Tool Calling Latency

    Fixing React Server Component Serialization Errors

    Fixing React Server Component Serialization Errors

    Next.js Route Handler Streaming with ReadableStream

    Next.js Route Handler Streaming with ReadableStream

    React Form Performance: Uncontrolled Inputs and FormData

    React Form Performance: Uncontrolled Inputs and FormData