patternpythonfastapiTip
FastAPI testing with TestClient — sync and async patterns
Viewed 0 times
FastAPI 0.100+, pytest, httpx 0.24+
TestClienttestingdependency_overridespytestintegration testhttpx
Problem
FastAPI apps need integration tests that exercise the full request lifecycle including dependencies, middleware, and exception handlers — not just unit tests of individual functions.
Solution
Use TestClient (sync) for most tests. For async test helpers, use httpx.AsyncClient with ASGITransport. Override dependencies with app.dependency_overrides.
from fastapi.testclient import TestClient
from myapp.main import app
from myapp.database import get_db
# Override DB dependency to use test DB
def override_get_db():
db = TestSessionLocal()
try:
yield db
finally:
db.close()
app.dependency_overrides[get_db] = override_get_db
client = TestClient(app)
def test_create_item():
response = client.post('/items/', json={'name': 'Foo', 'price': 1.5})
assert response.status_code == 201
assert response.json()['name'] == 'Foo'
# Async test with httpx
import pytest
import httpx
@pytest.mark.anyio
async def test_async_endpoint():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url='http://test') as ac:
resp = await ac.get('/items/')
assert resp.status_code == 200Why
TestClient wraps the ASGI app with requests under the hood, giving a synchronous interface that runs the full ASGI stack. dependency_overrides is a dict mapping original dependency callables to replacement callables — the cleanest way to inject test doubles.
Gotchas
- dependency_overrides is global state — reset it after each test or use a fixture with teardown
- TestClient doesn't start background tasks by default in some configurations — use with TestClient(app) as client: to trigger lifespan events
- WebSocket testing requires client.websocket_connect() context manager
- httpx.AsyncClient with ASGITransport requires anyio or pytest-asyncio
Context
Writing automated tests for FastAPI applications
Revisions (0)
No revisions yet.