全书目录

第二篇:FastAPI 完全指南 —— 软件城市政务大厅宇宙

第十九章:测试 —— 政务大厅上线前,先做消防演习

1 分钟 127 字 第 65 / 962 个阅读单元

FastAPI 官方测试教程的核心入口是 TestClient

py
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 要作为上下文管理器用。