Under The Hood
backend fastapi FastAPI 0.100+ (httpx / pytest-asyncio)

Testing with httpx.AsyncClient and ASGI In-Memory Transport

Last updated
Prerequisites:
pytest & pytest-asyncio basics
FastAPI dependency overrides
  • fastapi
  • testing
  • httpx
  • asyncclient
  • asgi
  • pytest
  • mocking

Read at your depth

The practical view

FastAPI recommends `httpx.AsyncClient` with `ASGITransport` for testing async endpoints with `pytest`. `async with AsyncClient(transport=ASGITransport(app=app), base_url='http://test') as ac: response = await ac.get('/users')`. This replaces the legacy synchronous `TestClient` for testing async endpoints, WebSockets, and lifespan events.

The same idea in other frameworks

fastapi equivalent
`AsyncClient(transport=ASGITransport(app=app))` with `app.dependency_overrides`.

Legacy vs modern

Synchronous TestClient vs Modern AsyncClient with Dependency Overrides

Synchronous `TestClient` cannot run inside native async pytest loops; `AsyncClient` tests async endpoints with clean dependency overrides.

before → after
Synchronous TestClient (Blocks Async Tests)
from fastapi.testclient import TestClient; client = TestClient(app) // ❌ Cannot await async fixtures
Modern AsyncClient + Dependency Overrides
async with AsyncClient(transport=ASGITransport(app=app)) as ac: ... // ✅ NEW: Pure async testing

Interview gotchas

Context

Interviewers test your knowledge of test transaction isolation.

The mechanical answer

Create a `pytest` async fixture that creates a nested database transaction (`connection.begin_nested()`) or runs a rollback transaction: execute the test, and in the fixture teardown, **call `transaction.rollback()`**. Override the `get_db` dependency using `app.dependency_overrides[get_db] = override_get_db`. All database queries execute against the real database schema inside an isolated transaction that is rolled back instantly when the test finishes.

Trap

Always call `app.dependency_overrides.clear()` in test cleanup fixtures to prevent test pollution across different test files.

Under The Hood — a multi-depth technical interview hub.

Third-party licenses Press ⌘ K to search.