Testing FastAPI applications

Difficulty: Intermediate

Question

How do you test FastAPI applications? How do you mock dependencies in tests?

Answer

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: 1. Create a `TestClient` with the FastAPI app 2. Override dependencies as needed 3. Make requests and assert responses 4. Clean up overrides after tests

Code examples

FastAPI testing with dependency override

from 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

Key points

Concepts covered

TestClient, pytest, dependency overrides, async testing