0
0
FastAPIframework~5 mins

Overriding dependencies in tests in FastAPI

Choose your learning style9 modes available
Introduction

Sometimes you want to replace parts of your app with simple versions during tests. This helps you test without using real services or data.

You want to test an API endpoint without calling a real database.
You need to simulate a user login without real authentication.
You want to check how your app behaves with fixed data instead of live data.
You want to speed up tests by skipping slow external services.
You want to isolate parts of your app to find bugs easily.
Syntax
FastAPI
app.dependency_overrides[original_dependency] = override_dependency

# After tests, clear overrides
app.dependency_overrides.clear()

original_dependency is the function or class your app normally uses.

override_dependency is your test version that returns fixed or mock data.

Examples
This replaces the real database connection with a test version during tests.
FastAPI
def get_db():
    # real database connection
    pass

def override_get_db():
    # test database or mock
    pass

app.dependency_overrides[get_db] = override_get_db
This makes the app always use a test user instead of real login.
FastAPI
def get_current_user():
    # real user authentication
    pass

def override_user():
    return {'username': 'testuser'}

app.dependency_overrides[get_current_user] = override_user
Sample Program

This example shows how to replace the real database connection with a test version. The test calls the endpoint and prints the response, which uses the overridden dependency.

FastAPI
from fastapi import FastAPI, Depends
from fastapi.testclient import TestClient

app = FastAPI()

def get_db():
    return "real database connection"

@app.get("/items/")
async def read_items(db=Depends(get_db)):
    return {"db": db}

# Override dependency for tests
def override_get_db():
    return "test database connection"

app.dependency_overrides[get_db] = override_get_db

client = TestClient(app)

def test_read_items():
    response = client.get("/items/")
    assert response.status_code == 200
    print(response.json())

# Run test function
test_read_items()
OutputSuccess
Important Notes

Always clear overrides after tests if you run multiple tests to avoid side effects.

Overrides let you test parts of your app without needing real external systems.

Summary

Override dependencies to replace real parts with test versions.

This helps isolate and speed up tests.

Use app.dependency_overrides to set and clear overrides.