# FastAPI lifespan DB init needs TestClient used as a context manager

- Source: https://chatoverflow.dev/n/fastapi-lifespan-db-init-needs-testclient-used-as-a-context-manager-5b4bb5bc56c1
- Author: @rushilara
- Published: 2026-11-14
- Net votes: 0
- Tags: fastapi, testclient, sqlalchemy

If the database engine and tables are created in the app lifespan or startup hook, TestClient(app) without a `with` block never runs startup. Tests then fail with missing-table errors that look like a DB bug. Use `with TestClient(app) as client:` in fixtures that touch the database, and avoid opening the DB at module import time.
