Full answer
fastapi.testclient.TestClient is Starlette's test client. It calls the ASGI app in-process, so tests are fast and need no network. It is built on HTTPX; Starlette 1.x prefers the httpx2 package (same API, pip install httpx2) and warns when only the older httpx is installed.
A typical test file:
from fastapi.testclient import TestClient
from app.main import app
client = TestClient(app)
def test_create_book():
r = client.post("/books", json={"title": "Godan", "copies": 2})
assert r.status_code == 201
assert r.json()["title"] == "Godan"Run with pytest. Test functions are normal def functions even if endpoints are async def; TestClient handles the event loop.
Request options mirror HTTPX: params=, json=, data= (form), files=, headers=, cookies=.
Patterns:
- Lifespan:
with TestClient(app) as client:runs startup and shutdown code (opening a database pool, loading a model). A module-level client withoutwithskips lifespan. - Dependency overrides:
app.dependency_overrides[get_db] = get_test_dbandapp.dependency_overrides[get_current_user] = lambda: fake_user. Clear them after each test (app.dependency_overrides.clear()), ideally in a fixture. - Fixtures: a pytest fixture that yields a client and a clean database per test.
- Validation tests: send bad input and assert 422 and the error
loc. - Auth tests: assert 401 without a token and 403 with the wrong role.
For tests that must be async themselves (calling async database code directly in the test), use httpx.AsyncClient with ASGITransport and an async test runner such as pytest-anyio or pytest-asyncio.
Aim tests at behaviour (status, body, side effects in the database), not at internal function calls.
import pytest
from fastapi import Depends, FastAPI, HTTPException
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
app = FastAPI()
class BookIn(BaseModel):
title: str = Field(min_length=1)
copies: int = Field(ge=0)
def get_store():
raise RuntimeError("real database not available in tests")
def current_user():
raise HTTPException(status_code=401, detail="Not authenticated")
@app.post("/books", status_code=201)
def create_book(book: BookIn, user: str = Depends(current_user), store: dict = Depends(get_store)):
store[book.title] = book.copies
return {"title": book.title, "copies": book.copies, "added_by": user}
@pytest.fixture
def client():
store = {}
app.dependency_overrides[get_store] = lambda: store
app.dependency_overrides[current_user] = lambda: "librarian"
with TestClient(app) as c:
yield c
app.dependency_overrides.clear()
def test_create_book(client):
r = client.post("/books", json={"title": "Godan", "copies": 2})
assert r.status_code == 201
assert r.json() == {"title": "Godan", "copies": 2, "added_by": "librarian"}
def test_rejects_negative_copies(client):
r = client.post("/books", json={"title": "Godan", "copies": -1})
assert r.status_code == 422
assert r.json()["detail"][0]["loc"] == ["body", "copies"]
def test_requires_login():
r = TestClient(app).post("/books", json={"title": "Godan", "copies": 1})
assert r.status_code == 401
if __name__ == "__main__":
code = pytest.main([__file__, "-qq", "-p", "no:cacheprovider", "-p", "no:warnings"])
print("pytest exit code:", int(code))
Standalone pytest file. Run it with `python file.py` or `pytest file.py`; it needs `pip install pytest httpx2`. Dependencies resolve in parameter order, so current_user is listed first and an anonymous request fails with 401 before the store is touched. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0, pytest 9.2.0): ... [100%] pytest exit code: 0
Key points
- TestClient calls the app in-process without a server
- httpx-style API: json=, params=, headers=
- Use 'with TestClient(app)' to run lifespan
- dependency_overrides swap DB and auth in tests
- Async tests use httpx.AsyncClient with ASGITransport
Common mistakes
- Creating the client without 'with' and wondering why startup code did not run
- Leaving dependency_overrides set and leaking fakes into other tests
- Testing against a shared real database that tests pollute
- Asserting only status codes and not the response body
Follow-ups
- How would you give each test a fresh database?
- When do you need httpx.AsyncClient instead of TestClient?
- How do you test an endpoint that sends an email?
Tips
- Show a fixture with dependency overrides
- Mention the lifespan and 'with' detail
- Cover a validation test and an auth test, not only the happy path