測試
FastAPI 的測試建立在 Starlette 的 TestClient 上,底層用 HTTPX。你用跟客戶端相同的方式打自己的應用,斷言狀態碼與 JSON,不必開真實埠。
用 TestClient 打自己的 app
from fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
@app.get("/items/{item_id}")
def read_item(item_id: int):
return {"item_id": item_id}
client = TestClient(app)
def test_read_item():
response = client.get("/items/3")
assert response.status_code == 200
assert response.json() == {"item_id": 3}
def test_read_item_invalid():
response = client.get("/items/not-an-int")
assert response.status_code == 422
pip install / uv add 了 fastapi[standard] 就會帶上 HTTPX。測試檔用 pytest 跑:uv run pytest。
驗證錯誤、404、建立成功的 201,都應該各有一筆測試。文件會過期,測試比較不容易。
覆寫依賴,隔離外部世界
路徑函式若 Depends(get_db) 或 Depends(get_current_user),測試不該連上正式資料庫或真的發 JWT:
def fake_current_user():
return {"username": "tester"}
app.dependency_overrides[get_current_user] = fake_current_user
response = client.get("/me")
assert response.json()["username"] == "tester"
app.dependency_overrides.clear()
這是依賴注入在測試上的回報:端點邏輯與「如何取得使用者」被切開,單元測試只測前者。
非同步路徑函式一樣可用 TestClient;它會在內部跑完 async。若要測 WebSocket 或真正的 async fixture,再看官方進階測試與 httpx.AsyncClient。