Mocking delle dipendenze nei test FastAPI
Impari a isolare gli endpoint FastAPI nei test sovrascrivendo le dipendenze e simulando i servizi esterni.
Mocking delle dipendenze nei test FastAPI è una lezione FastAPI Backend Development Bootcamp gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento FastAPI Backend Development Bootcamp, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso FastAPI Backend Development Bootcamp include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
Why Mock Dependencies?
When testing a FastAPI endpoint, you often want to isolate the route logic from external systems like databases, payment gateways, or third-party APIs.
Mocking replaces those slow or unreliable parts with predictable fakes so your tests stay fast and deterministic.
FastAPI Dependency Overrides
FastAPI exposes app.dependency_overrides, a dictionary that maps a real dependency to a fake one during testing.
This is the cleanest way to swap a database session or auth check without touching production code.
app.dependency_overrides[get_db] = override_get_dbA Dependency to Override
Imagine an endpoint that depends on a database session.
from fastapi import Depends
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@app.get("/users/{uid}")
def read_user(uid: int, db=Depends(get_db)):
return db.query(User).get(uid)Providing a Fake Session
In your test, define a function that yields an in-memory or test session, then register it as an override.
def override_get_db():
db = TestingSessionLocal()
try:
yield db
finally:
db.close()
app.dependency_overrides[get_db] = override_get_dbClearing Overrides
Always clear overrides after a test so they do not leak into other tests.
Use app.dependency_overrides.clear() in teardown or a pytest fixture finalizer.
app.dependency_overrides.clear()Mocking with unittest.mock
For non-dependency code such as a helper that calls an external API, use unittest.mock.patch to replace the function.
from unittest.mock import patch
with patch("app.services.send_email") as mock_send:
mock_send.return_value = True
response = client.post("/signup", json=payload)
mock_send.assert_called_once()Using MagicMock Return Values
A MagicMock lets you script return values and inspect how it was called.
from unittest.mock import MagicMock
fake_client = MagicMock()
fake_client.charge.return_value = {"status": "ok"}Mocking Async Functions
FastAPI is async-friendly. To mock an async dependency, use AsyncMock so awaiting it works correctly.
from unittest.mock import AsyncMock
mock_repo = AsyncMock()
mock_repo.get_user.return_value = {"id": 1, "name": "Ada"}Mocking Auth Dependencies
To bypass authentication in a test, override the auth dependency to return a fake user.
def fake_current_user():
return User(id=1, role="admin")
app.dependency_overrides[get_current_user] = fake_current_userVerifying Mock Calls
Mocks record every interaction. Assert that your code called the dependency the expected way.
mock_send.assert_called_once_with(to="a@b.com")
assert mock_repo.save.call_count == 1Fixture-Based Overrides
Wrap overrides in a pytest fixture for reuse and automatic cleanup.
import pytest
@pytest.fixture
def client_with_db():
app.dependency_overrides[get_db] = override_get_db
yield TestClient(app)
app.dependency_overrides.clear()Quick Check
Test your mocking knowledge.
Recap
You learned how to isolate FastAPI endpoints in tests:
- dependency_overrides swaps dependencies like DB sessions or auth
- patch / MagicMock / AsyncMock fake external functions
- Always clear overrides after each test
Mocking keeps tests fast, deterministic, and focused on your own logic.
Domande Frequenti
La lezione «Mocking delle dipendenze nei test FastAPI» è gratuita?
Sì — il testo completo di «Mocking delle dipendenze nei test FastAPI» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso FastAPI Backend Development Bootcamp, passa a CoddyKit PRO. Il corso FastAPI Backend Development Bootcamp include 4 lezioni in totale.
Cosa imparerò in «Mocking delle dipendenze nei test FastAPI»?
Impari a isolare gli endpoint FastAPI nei test sovrascrivendo le dipendenze e simulando i servizi esterni. Eserciti FastAPI Backend Development Bootcamp con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare FastAPI Backend Development Bootcamp?
Non è richiesta alcuna esperienza precedente. FastAPI Backend Development Bootcamp su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.
Quanto tempo richiede la lezione «Mocking delle dipendenze nei test FastAPI»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione FastAPI Backend Development Bootcamp?
Sì. Ogni lezione FastAPI Backend Development Bootcamp include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Unit test con Pytest
- Test di integrazione degli endpoint FastAPI
- Debug delle applicazioni FastAPI
- Mocking delle dipendenze nei test FastAPI