Set app.dependency_overrides to swap a dependency for a test version, such as a test database session, a fake current user or a mock LLM client; clear the overrides after each test.
import pytest
from fastapi.testclient import TestClient
from app.main import app, get_db, get_current_user
def override_get_db():
db = TestingSessionLocal()
try:
yield db
finally:
db.close()
@pytest.fixture
def client():
app.dependency_overrides[get_db] = override_get_db
app.dependency_overrides[get_current_user] = lambda: FakeUser(id=1, is_admin=False)
yield TestClient(app)
app.dependency_overrides.clear()Use a separate test database (SQLite or a throwaway PostgreSQL instance) and roll back transactions between tests so they stay independent.