[{"data":1,"prerenderedAt":87},["ShallowReactive",2],{"qa-\u002Ffastapi\u002Ftesting\u002Fdependency-overrides":3},{"page":4,"siblings":78,"blog":70},{"id":5,"title":6,"body":7,"description":11,"difficulty":14,"extension":15,"framework":16,"frameworkSlug":17,"meta":18,"navigation":19,"order":20,"path":21,"questions":22,"questionsCount":69,"related":70,"seo":71,"seoDescription":72,"stem":73,"subtopic":6,"topic":74,"topicSlug":75,"updated":76,"__hash__":77},"qa\u002Ffastapi\u002Ftesting\u002Fdependency-overrides.md","Dependency Overrides",{"type":8,"value":9,"toc":10},"minimark",[],{"title":11,"searchDepth":12,"depth":12,"links":13},"",2,[],"medium","md","FastAPI","fastapi",{},true,3,"\u002Ffastapi\u002Ftesting\u002Fdependency-overrides",[23,28,32,36,40,44,48,53,57,61,65],{"id":24,"difficulty":25,"q":26,"a":27},"dependency-overrides-basics","easy","What is `app.dependency_overrides` and how do you use it in tests?","`app.dependency_overrides` is a dict on the `FastAPI` instance. Map an original\ndependency function to a replacement callable — FastAPI calls the replacement\ninstead during test requests.\n\n```python\nfrom app.main import app\nfrom app.auth import get_current_user\nfrom fastapi.testclient import TestClient\n\ndef mock_user():\n    return {\"id\": 1, \"name\": \"Alice\", \"role\": \"admin\"}\n\napp.dependency_overrides[get_current_user] = mock_user\n\nclient = TestClient(app)\n\ndef test_protected_endpoint():\n    resp = client.get(\"\u002Fadmin\u002Fstats\")\n    assert resp.status_code == 200\n```\n\nRule of thumb: use `dependency_overrides` to replace any injected function —\nDB sessions, auth, settings, external API clients — without touching app code.\n",{"id":29,"difficulty":14,"q":30,"a":31},"cleanup-overrides","How do you ensure dependency overrides don't leak between tests?","Use a pytest `autouse` fixture to clear overrides after every test:\n\n```python\nimport pytest\nfrom app.main import app\n\n@pytest.fixture(autouse=True)\ndef reset_dependency_overrides():\n    yield\n    app.dependency_overrides.clear()\n```\n\nOr clear per-override:\n```python\n@pytest.fixture\ndef with_mock_user():\n    app.dependency_overrides[get_current_user] = lambda: {\"id\": 1}\n    yield\n    del app.dependency_overrides[get_current_user]\n```\n\nRule of thumb: always clean up overrides in fixture teardown — a leaked override\nin one test silently causes wrong behaviour in subsequent tests.\n",{"id":33,"difficulty":25,"q":34,"a":35},"override-return-value","Does the override function need the same signature as the original dependency?","No — the override only needs to return a compatible value. FastAPI replaces the\nentire callable, so the override's parameters are independently resolved by DI.\n\n```python\n# Original dep — reads from DB\nasync def get_current_user(token: str = Depends(oauth2_scheme)):\n    payload = decode_jwt(token)\n    return await db.get_user(payload[\"sub\"])\n\n# Override — returns a hardcoded user, no token needed\ndef mock_admin_user():\n    return User(id=1, name=\"Admin\", role=\"admin\")\n\napp.dependency_overrides[get_current_user] = mock_admin_user\n```\n\nThe override receives its own deps from DI — if it has parameters, they'll be\ninjected. If it has none, it just returns the hardcoded value.\n\nRule of thumb: keep override functions as simple as possible — bare lambdas or\nzero-argument functions returning fake objects are ideal for tests.\n",{"id":37,"difficulty":14,"q":38,"a":39},"override-with-settings","How do you override `BaseSettings` in tests using dependency overrides?","Override the `get_settings` dependency (the `@lru_cache` wrapper):\n\n```python\nfrom app.config import get_settings, Settings\nfrom app.main import app\n\ndef test_settings():\n    test_settings = Settings(\n        database_url=\"sqlite+aiosqlite:\u002F\u002F\u002F:memory:\",\n        secret_key=\"test-only-secret\",\n        debug=True,\n    )\n    app.dependency_overrides[get_settings] = lambda: test_settings\n\n    with TestClient(app) as client:\n        resp = client.get(\"\u002Fconfig\")\n        assert resp.json()[\"debug\"] is True\n\n    app.dependency_overrides.clear()\n```\n\nAlso clear the `@lru_cache` to prevent stale settings:\n```python\nget_settings.cache_clear()\n```\n\nRule of thumb: always pair `dependency_overrides[get_settings]` with\n`get_settings.cache_clear()` to prevent the cached production settings from\nbeing used despite the override.\n",{"id":41,"difficulty":14,"q":42,"a":43},"override-db-session","Show the standard pattern for replacing the DB session dependency in tests.","```python\n# conftest.py\nimport pytest\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker, Session\nfrom fastapi.testclient import TestClient\nfrom app.main import app\nfrom app.db.session import get_db\nfrom app.db.base import Base\n\nTEST_ENGINE = create_engine(\"sqlite:\u002F\u002F\u002F:memory:\", connect_args={\"check_same_thread\": False})\nTestingSessionLocal = sessionmaker(bind=TEST_ENGINE)\n\n@pytest.fixture(scope=\"module\", autouse=True)\ndef create_tables():\n    Base.metadata.create_all(bind=TEST_ENGINE)\n    yield\n    Base.metadata.drop_all(bind=TEST_ENGINE)\n\n@pytest.fixture\ndef db_session():\n    session = TestingSessionLocal()\n    try:\n        yield session\n    finally:\n        session.rollback()\n        session.close()\n\n@pytest.fixture\ndef client(db_session):\n    def override_get_db():\n        yield db_session\n    app.dependency_overrides[get_db] = override_get_db\n    with TestClient(app) as c:\n        yield c\n    app.dependency_overrides.clear()\n```\n\nRule of thumb: roll back the test session instead of committing — it gives\neach test an isolated, empty state without truncating tables.\n",{"id":45,"difficulty":14,"q":46,"a":47},"override-external-api","How do you mock an external HTTP API call injected as a dependency?","Inject the HTTP client as a dependency, then override it in tests:\n\n```python\n# In app code\nimport httpx\n\nasync def get_http_client() -> httpx.AsyncClient:\n    async with httpx.AsyncClient() as client:\n        yield client\n\n@app.get(\"\u002Fweather\")\nasync def weather(city: str, client: httpx.AsyncClient = Depends(get_http_client)):\n    resp = await client.get(f\"https:\u002F\u002Fapi.weather.com\u002F{city}\")\n    return resp.json()\n```\n\n```python\n# In tests — replace with a respx mock\nimport respx\nimport httpx\n\n@respx.mock\ndef test_weather(client):\n    respx.get(\"https:\u002F\u002Fapi.weather.com\u002FLondon\").mock(\n        return_value=httpx.Response(200, json={\"temp\": 15})\n    )\n    resp = client.get(\"\u002Fweather?city=London\")\n    assert resp.json()[\"temp\"] == 15\n```\n\nOr inject a fake client via override:\n```python\nasync def fake_http_client():\n    yield FakeAsyncClient()\n\napp.dependency_overrides[get_http_client] = fake_http_client\n```\n\nRule of thumb: inject HTTP clients as dependencies rather than instantiating\nthem inside handlers — it makes them mockable without `patch()`.\n",{"id":49,"difficulty":50,"q":51,"a":52},"partial-override","hard","How do you override only part of a dependency chain (one level deep)?","Override just the sub-dependency, leaving higher-level deps intact:\n\n```python\n# Dependency chain: get_db → get_current_user → require_admin\n# We want to test require_admin with a specific user but real DB logic\n\ndef fixed_user():\n    return User(id=99, name=\"Test Admin\", role=\"admin\")\n\n# Override only get_current_user — get_db still uses real DI\napp.dependency_overrides[get_current_user] = fixed_user\n\n# require_admin still calls its Depends(get_current_user) — but gets our mock\n```\n\nFastAPI resolves the override at the point where the original dep is declared —\nanything that `Depends()` on it gets the override's return value.\n\nRule of thumb: override at the lowest practical level — overriding `get_current_user`\n(not `require_admin`) tests `require_admin`'s logic with controlled user data.\n",{"id":54,"difficulty":14,"q":55,"a":56},"class-dep-override","How do you override a class-based dependency in FastAPI tests?","Class-based deps are instantiated by FastAPI on each call. Override with another\ncallable (class, function, or lambda) that returns a compatible object:\n\n```python\nclass PaginationDep:\n    def __init__(self, page: int = 1, size: int = 20):\n        self.skip = (page - 1) * size\n        self.limit = size\n\n# Override with a fixed pagination\nclass FixedPagination:\n    skip = 0\n    limit = 5\n\napp.dependency_overrides[PaginationDep] = FixedPagination\n\ndef test_first_page(client):\n    resp = client.get(\"\u002Fitems\")\n    data = resp.json()\n    assert len(data) \u003C= 5\n```\n\nRule of thumb: match the override's public interface (attributes\u002Fmethods your\nhandler uses) rather than its constructor — duck typing is sufficient.\n",{"id":58,"difficulty":14,"q":59,"a":60},"override-scope-per-test","How do you apply a dependency override to only one test without affecting others?","Use a pytest fixture with function scope (the default):\n\n```python\n@pytest.fixture\ndef admin_override():\n    app.dependency_overrides[get_current_user] = lambda: {\"id\": 1, \"role\": \"admin\"}\n    yield\n    del app.dependency_overrides[get_current_user]\n\ndef test_admin_only(client, admin_override):\n    resp = client.delete(\"\u002Fusers\u002F99\")\n    assert resp.status_code == 200\n\ndef test_normal_user(client):\n    # admin_override not active — real get_current_user used\n    resp = client.delete(\"\u002Fusers\u002F99\")\n    assert resp.status_code == 403\n```\n\nRule of thumb: use per-test fixtures with explicit teardown for scoped overrides —\ndon't set overrides directly in test bodies without a cleanup mechanism.\n",{"id":62,"difficulty":50,"q":63,"a":64},"verify-dep-called","How do you verify that a dependency was called with specific arguments in a test?","Replace the dependency with a `MagicMock` or a spy function:\n\n```python\nfrom unittest.mock import MagicMock, call\n\nmock_audit = MagicMock()\n\ndef audit_override(request: Request, user = Depends(get_current_user)):\n    mock_audit(path=str(request.url), user_id=user[\"id\"])\n\napp.dependency_overrides[audit_dep] = audit_override\n\ndef test_audit_logged(client):\n    client.get(\"\u002Fitems\")\n    mock_audit.assert_called_once()\n    call_args = mock_audit.call_args\n    assert call_args.kwargs[\"user_id\"] == 1\n```\n\nRule of thumb: spy on dependencies rather than internal functions — testing\nthrough the DI graph tests the real integration path.\n",{"id":66,"difficulty":50,"q":67,"a":68},"dependency-override-with-yield","Can you use a yield function as a dependency override?","Yes — yield-based overrides work exactly like regular yield dependencies:\n\n```python\nclass FakeDB:\n    def __init__(self):\n        self.data = [{\"id\": 1, \"name\": \"Alice\"}]\n\n    def get_all(self):\n        return self.data\n\nasync def fake_get_db():\n    db = FakeDB()\n    db.data.append({\"id\": 2, \"name\": \"Bob\"})  # setup\n    yield db\n    db.data.clear()                              # teardown (after handler)\n\napp.dependency_overrides[get_db] = fake_get_db\n```\n\nThe teardown (after `yield`) still runs after the handler completes — useful for\nresetting state in the override itself.\n\nRule of thumb: use yield overrides when the fake resource needs setup and\ncleanup; use simple lambdas\u002Ffunctions for stateless fakes.\n",11,null,{"description":11},"FastAPI dependency override interview questions — app.dependency_overrides, isolating tests, mocking auth, DB session swapping and cleanup patterns.","fastapi\u002Ftesting\u002Fdependency-overrides","Testing","testing","2026-06-20","175Uw5rR-p9_L-Whet4tK7RU-i9X1_m80vF3wA-Egnk",[79,83,86],{"subtopic":80,"path":81,"order":82},"TestClient","\u002Ffastapi\u002Ftesting\u002Ftest-client",1,{"subtopic":84,"path":85,"order":12},"Async Testing","\u002Ffastapi\u002Ftesting\u002Fasync-testing",{"subtopic":6,"path":21,"order":20},1782244113548]