📖 Scenario: You are building a simple FastAPI app that depends on a function to get a message. For testing, you want to replace this function with a fake one to control the output.
🎯 Goal: Create a FastAPI app with a dependency function, then override this dependency in a test to return a fixed message.
📋 What You'll Learn
Create a dependency function called get_message that returns the string 'Hello from dependency!'
Create a FastAPI app instance called app
Create a GET endpoint at / that uses get_message as a dependency and returns a JSON with the message
Create a test client using TestClient from fastapi.testclient
Override the get_message dependency in the test to return 'Hello from override!'
Write a test function called test_read_main that uses the test client to call / and asserts the JSON response matches the overridden message
💡 Why This Matters
🌍 Real World
Overriding dependencies is useful when you want to test parts of your FastAPI app without relying on real external services or complex logic.
💼 Career
Many jobs require writing tests for APIs. Knowing how to override dependencies helps you write isolated, reliable tests for FastAPI applications.
Progress0 / 4 steps
1
Create the dependency function and FastAPI app
Create a function called get_message that returns the string 'Hello from dependency!'. Then create a FastAPI app instance called app.
FastAPI
Hint
Use def get_message(): to define the function and app = FastAPI() to create the app.
2
Add a GET endpoint using the dependency
Add a GET endpoint at / to the app that uses get_message as a dependency with Depends. The endpoint should return a dictionary with the key message and the value from get_message.
FastAPI
Hint
Use @app.get("/") to create the route and Depends(get_message) to inject the dependency.
3
Create a test client and override the dependency
Import TestClient from fastapi.testclient. Create a test client called client for the app. Then override the get_message dependency in app.dependency_overrides to a new function that returns 'Hello from override!'.
FastAPI
Hint
Create client = TestClient(app) and override with app.dependency_overrides[get_message] = override_get_message.
4
Write the test function to check the overridden dependency
Write a test function called test_read_main that uses the client to send a GET request to /. Assert that the response status code is 200 and the JSON response is {"message": "Hello from override!"}.
FastAPI
Hint
Use client.get("/") and assert the status and JSON response.
Practice
(1/5)
1. What is the main purpose of overriding dependencies in FastAPI tests?
easy
A. To replace real dependencies with test versions for isolated testing
B. To speed up the server in production
C. To add new routes dynamically
D. To change the database schema automatically
Solution
Step 1: Understand dependency overriding concept
Overriding dependencies allows replacing real parts like database or external services with test doubles.
Step 2: Identify the testing benefit
This replacement isolates tests and makes them faster and more reliable.
Final Answer:
To replace real dependencies with test versions for isolated testing -> Option A
Quick Check:
Override dependencies = isolate tests [OK]
Hint: Override to isolate and speed tests, not for production changes [OK]
Common Mistakes:
Thinking overrides speed up production
Confusing overrides with adding routes
Assuming overrides change database schema
2. Which of the following is the correct way to override a dependency in FastAPI for testing?
easy
A. app.override[original_dep] = test_dep
B. app.override_dependency(original_dep, test_dep)
C. app.dependency_overrides[original_dep] = test_dep
D. app.set_dependency_override(original_dep, test_dep)
Solution
Step 1: Recall FastAPI override syntax
FastAPI uses the dictionary app.dependency_overrides to map original dependencies to test versions.
Step 2: Match correct syntax
Assigning test_dep to app.dependency_overrides[original_dep] is the correct way.
Final Answer:
app.dependency_overrides[original_dep] = test_dep -> Option C
Quick Check:
Use dependency_overrides dict = A [OK]
Hint: Use app.dependency_overrides dictionary to override [OK]
Common Mistakes:
Using non-existent methods like override_dependency
Trying to assign to app.override
Calling set_dependency_override which doesn't exist
3. Given this test code snippet, what will be the output of the test client call?
The original get_number returns 10, but it is overridden by override_get_number returning 42.
Step 2: Analyze the endpoint response
The endpoint uses Depends(get_number), so it will receive 42 from the override.
Final Answer:
{"number": 42} -> Option A
Quick Check:
Override returns 42, so response = {"number": 42} [OK]
Hint: Override changes return value used by endpoint [OK]
Common Mistakes:
Assuming original dependency runs despite override
Expecting null instead of overridden value
Thinking override causes runtime error
4. You wrote this test code but it raises an error. What is the likely cause?
app.dependency_overrides[get_data] = override_get_data
# test code runs here
app.dependency_overrides.clear()
Error: KeyError during test execution.
medium
A. Calling clear() removes all overrides, but test still uses them
B. Not resetting dependency_overrides before tests causes conflict
C. Using clear() on dependency_overrides dictionary is invalid
D. Overriding dependencies must be done inside a fixture or context manager
Solution
Step 1: Understand dependency_overrides lifecycle
Overrides should be reset before each test to avoid conflicts from previous tests.
Step 2: Identify cause of the test error
If dependency_overrides is not cleared before tests, leftover overrides cause unexpected errors.
Final Answer:
Not resetting dependency_overrides before tests causes conflict -> Option B
Quick Check:
Reset overrides before tests to avoid conflicts [OK]
Hint: Clear overrides before tests to prevent conflicts [OK]
Common Mistakes:
Assuming clear() is invalid method
Not using fixtures to manage overrides lifecycle
Believing overrides persist safely across tests
5. You want to test an endpoint that depends on a database session. How do you correctly override the database dependency to use a test session only during tests?
hard
A. Use a global variable to switch between real and test sessions inside db_session
B. Replace the db_session function globally in your app code with test session
C. Call get_test_db_session inside the endpoint instead of using Depends
D. Set app.dependency_overrides[db_session] = get_test_db_session before tests and clear after
Solution
Step 1: Use dependency_overrides for test isolation
Override the database session dependency only during tests to avoid affecting production code.
Step 2: Properly set and clear overrides
Assign the test session function to app.dependency_overrides[db_session] before tests and clear it after tests.
Final Answer:
Set app.dependency_overrides[db_session] = get_test_db_session before tests and clear after -> Option D
Quick Check:
Override dependency only in tests, then clear [OK]
Hint: Override dependency only in tests, clear after [OK]
Common Mistakes:
Replacing functions globally breaks production code
Using global flags inside dependency is error-prone
Calling test session inside endpoint breaks separation
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.