Difficulty: Intermediate
How do you test FastAPI applications? How do you mock dependencies in tests?
FastAPI provides TestClient (from starlette.testclient) which wraps the ASGI app and allows synchronous HTTP testing with a requests-like API. For async tests, use httpx.AsyncClient with ASGITransport.
Dependency overriding is the key pattern for testing: use app.dependency_overrides to replace real dependencies (DB, auth) with test doubles.
Test structure:
TestClient with the FastAPI appfrom fastapi.testclient import TestClient
from main import app, get_current_user
import pytest
# Override auth dependency
def mock_user():
return {"id": 1, "name": "Test User"}
@pytest.fixture
def client():
app.dependency_overrides[get_current_user] = mock_user
with TestClient(app) as c:
yield c
app.dependency_overrides.clear()
def test_get_profile(client):
response = client.get("/me")
assert response.status_code == 200
assert response.json()["name"] == "Test User"
# Async testing with httpx
import pytest_asyncio
from httpx import AsyncClient, ASGITransport
@pytest.mark.asyncio
async def test_async_endpoint():
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as ac:
response = await ac.get("/items")
assert response.status_code == 200
TestClient, pytest, dependency overrides, async testing