How do you test a FastAPI endpoint without calling the real database?
Options
- You cannot do it without starting a real database
TestClientplusdependency_overrides[get_db]fake (Correct option)- Patch
fastapi.FastAPIitself in the test setup - Run the server and call it with curl in the tests
Answer
Use TestClient(app) and replace the DB dependency with app.dependency_overrides[get_db] = fake_db
Why
TestClient sends requests to your app in memory, without starting a real server.
Because FastAPI uses dependency injection, you can swap any dependency for the test: app.dependency_overrides[get_db] = lambda: fake_db.
Remember to clear the overrides after each test (a fixture is a good place).
client = TestClient(app)
app.dependency_overrides[get_db] = lambda: FakeDB()
def test_read_user():
r = client.get("/users/1")
assert r.status_code == 200Remember
FastAPI tests: TestClient + dependency_overrides.