Dùng TestClient cho synchronous-style test của async endpoints.
Override dependencies để isolate tests.
python
from fastapi.testclient import TestClient
import pytest
def override_get_db():
yield TestingSessionLocal()
app.dependency_overrides[get_db] = override_get_db
client = TestClient(app)
def test_create_user():
res = client.post("/users", json={
"name": "Alice", "email": "alice@test.com"
})
assert res.status_code == 201
assert res.json()["email"] == "alice@test.com"
# Async test
@pytest.mark.asyncio
async def test_async():
async with AsyncClient(app=app, base_url="http://test") as ac:
res = await ac.get("/users/1")
assert res.status_code == 200