Testing FastAPI ApplicationsLesson 5.1
How to set up pytest and TestClient for FastAPI testing
TestClient, httpx transport, pytest setup, test file structure, conftest.py, pytest fixtures, test database, TESTING environment flag
Testing Setup with pytest and TestClient
FastAPI's TestClient wraps httpx to send HTTP requests to your app without starting a real server. It is synchronous regardless of whether your routes are async.
Install
pip install pytest httpxBasic test
# tests/test_main.py
from fastapi.testclient import TestClient
from app.main import app
client = TestClient(app)
def test_read_root():
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"message": "Hello, FastAPI"}
def test_create_item():
response = client.post("/items/", json={"name": "Widget", "price": 9.99})
assert response.status_code == 201
assert response.json()["name"] == "Widget"
conftest.py for shared fixtures
# tests/conftest.py
import pytest
from fastapi.testclient import TestClient
from app.main import app
@pytest.fixture
def client():
with TestClient(app) as c:
yield c
Using the context manager form of TestClient triggers FastAPI's startup and shutdown events, which is required when your app registers event handlers. Put shared fixtures in conftest.py โ pytest discovers them automatically without import.
Running tests
pytest -v
pytest tests/test_main.py::test_read_root # single test