FastAPI rất testable nhờ TestClient (xây trên Starlette/httpx) và hệ thống dependency injection của nó, vốn khiến việc mock dependency trở nên dễ dàng. Test thường dùng pytest và TestClient để gửi request đến app mà không cần một server đang chạy.
Test endpoint cơ bản với TestClient
fastapi.testclient TestClient
main app
client = TestClient(app)
():
response = client.get()
response.status_code ==
response.json() == {: }
():
response = client.post(, json={: , : })
response.status_code ==
response.json()[] ==
():
response = client.post(, json={: })
response.status_code ==
