How do you test FastAPI routes, including routes protected by auth?medium
FastAPI's TestClient wraps the app in a synchronous requests-compatible interface for standard pytest tests. Override dependencies using app.dependency_overrides to swap real auth or DB dependencies with mocks that return test data — no real HTTP server needed.
TestClient is built on httpx and runs the ASGI app in-process, making tests fast with no port binding. app.dependency_overrides is a dict mapping real dependency callables to replacement functions. Set it up before the test and clear it after — pytest fixtures with setup/teardown are the clean pattern. For async tests use httpx.AsyncClient with pytest-asyncio. Always test 422 validation errors explicitly to confirm that your Pydantic models reject bad input as expected.