How do router-level and app-level dependencies affect dependency override testing?
This tests FastAPI dependency hierarchy and test isolation. A strong answer states overrides are global to the app, so router-specific deps need scoped fixtures to prevent cross-test leaks. A red flag is claiming APIRouter has its own override registry.
What's really being asked
FastAPI dependency injection resolution order and the global nature of app.dependency_overrides. Interviewers want to know if you understand that APIRouter does not maintain a separate container; dependencies declared on a router are resolved through the main app. This matters because in a large codebase with many routers, naive override strategies can leak state between tests or accidentally affect unrelated routes.
The full answer
First, state that dependency overrides in FastAPI are always applied to the app instance, never to an APIRouter directly. Second, explain that router-level dependencies are overridden by assigning to app.dependency_overrides[original_dep] = mock_dep before the TestClient is initialized or during a fixture setup. Third, describe the importance of cleanup: overrides persist on the app object, so you must reset app.dependency_overrides.clear() or restore the original mapping after each test to prevent cross-test contamination. Fourth, mention that if a dependency is used in only one router, you can still override it globally on the app, but you should isolate the override using a pytest fixture with setup and teardown or a context manager wrapper. Fifth, note that creating separate app instances per router for testing is an anti-pattern because it diverges from production wiring; instead, use the real app but manage override state carefully. Sixth, add that you can verify the override is active by inspecting app.dependency_overrides inside the fixture or by asserting on the mock call count in the test.
The mistakes people make
Claiming that APIRouter has its own dependency_overrides dictionary. Suggesting that you must override the dependency on every individual path operation instead of once at the app level. Proposing to mutate the router object directly rather than using the app's override registry. Forgetting to clean up overrides, which causes flaky tests when the test runner reuses the app instance. Asserting that router-level dependencies are invisible to the main app and therefore cannot be overridden. Recommending monkeypatching the dependency function in its module instead of using the supported override mechanism, which breaks when FastAPI caches the dependency callable.
What usually comes next
How would you override a dependency that uses yield and has cleanup logic? What happens if two routers use the same dependency name but different functions? How do you handle overrides when running tests in parallel with pytest-xdist? Would you structure your app differently to make testing easier, such as using a factory pattern?
A concrete example
Suppose you have an APIRouter for billing with a router-level dependency get_payment_gateway. In your main app, you include the router and its dependency. During testing, you write a fixture that sets app.dependency_overrides[get_payment_gateway] = lambda: MockGateway(), yields the TestClient, and then calls app.dependency_overrides.clear() in the teardown. This ensures that only tests using that fixture see the override, and subsequent tests receive the real dependency. If you skipped the cleanup, a test in the user router might accidentally inherit the mock gateway, causing a false pass.
Interview question
Which strategy correctly isolates a router-level dependency override when testing a FastAPI application with multiple routers?
- a.Apply the override to app.dependency_overrides in a fixture and clear it during teardown.Correct
- b.Apply the override directly to the APIRouter before including it in the app.
- c.Create a separate FastAPI app instance for each router during testing.
- d.Monkeypatch the dependency function in its original module within the test.
Why? this is the answer
FastAPI stores dependency overrides globally on the app instance, so the correct approach is to use app.dependency_overrides inside a fixture and clear it during teardown to prevent state leaks. Option B is tempting because the dependency is declared on the router, but APIRouter does not have its own override registry.
Just read this? Test yourself on what you have been reading.
Read the original → fastapi.tiangolo.com
- #fastapi
- #dependency-injection
- #testing
- #python
- #api-router
Put your scrolling time to good use
Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.
The iPhone app is on the way
We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.
Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.
We are hiring for this. Open roles that interview on fastapi — each one lists the topics its interview covers.
See open roles