FastAPI 官方测试教程的核心入口是 TestClient。
from fastapi.testclient import TestClient
from .main import app
def test_root():
with TestClient(app) as client:
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"message": "政务大厅已开门"}为什么这里用 with TestClient(app)?
因为 Starlette 官方文档特别提醒:如果你想让 lifespan 真正跑起来,TestClient 要作为上下文管理器用。