FastAPI Tests
Use TestClient from Starlette/FastAPI to make HTTP calls in tests without a real server.
Use TestClient from Starlette/FastAPI to make HTTP calls in tests without a real server.
from fastapi.testclient import TestClient
from myapp.main import app
client = TestClient(app)
def test_read_root():
resp = client.get("/")
assert resp.status_code == 200
assert resp.json() == {"message": "Hello World"}
def test_create_user():
resp = client.post("/users/", json={"name": "Alice", "email": "alice@example.com"})
assert resp.status_code == 201
assert resp.json()["name"] == "Alice"
Override dependencies with app.dependency_overrides to mock database or auth in tests.