Repaso
EspaƱol
TestingIntermediateTST-19

How do you test a FastAPI endpoint without calling the real database?

Options

  1. You cannot do it without starting a real database
  2. TestClient plus dependency_overrides[get_db] fake (Correct option)
  3. Patch fastapi.FastAPI itself in the test setup
  4. 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 == 200

Remember

FastAPI tests: TestClient + dependency_overrides.

Key terms

Practice this question in Repaso