Bird
Raised Fist0
FastAPIframework~20 mins

Overriding dependencies in tests in FastAPI - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
FastAPI Dependency Override Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output when overriding a dependency in FastAPI test client?

Given this FastAPI app with a dependency that returns a user ID, and a test that overrides this dependency, what will the test client receive as the response?

FastAPI
from fastapi import FastAPI, Depends
from fastapi.testclient import TestClient

app = FastAPI()

def get_user_id():
    return 42

@app.get("/user")
async def read_user(user_id: int = Depends(get_user_id)):
    return {"user_id": user_id}

client = TestClient(app)

def override_get_user_id():
    return 99

app.dependency_overrides[get_user_id] = override_get_user_id

response = client.get("/user")
print(response.json())
A{"user_id": 42}
B{"user_id": 99}
C{"user_id": null}
DRaises a RuntimeError
Attempts:
2 left
💡 Hint

Think about what the override function returns and how FastAPI uses dependency overrides in tests.

📝 Syntax
intermediate
2:00remaining
Which option correctly overrides a FastAPI dependency in a test?

Choose the correct way to override the get_db dependency in a FastAPI test.

FastAPI
def get_db():
    return "real_db"

app = FastAPI()

@app.get("/items")
async def read_items(db=Depends(get_db)):
    return {"db": db}

client = TestClient(app)
Aapp.dependency_overrides[get_db] = lambda: "test_db"
Bapp.override_dependency(get_db, lambda: "test_db")
Capp.dependency_overrides[get_db] = "test_db"
Dapp.dependency_overrides[get_db()] = lambda: "test_db"
Attempts:
2 left
💡 Hint

Remember the syntax for dependency_overrides dictionary keys and values.

🔧 Debug
advanced
2:00remaining
Why does this FastAPI test fail with a 422 error despite overriding the dependency?

Consider this FastAPI endpoint and test. The test overrides the dependency but the response status code is 422. Why?

FastAPI
from fastapi import FastAPI, Depends
from fastapi.testclient import TestClient

app = FastAPI()

def get_token():
    return "real_token"

@app.get("/secure")
async def secure_route(token: str = Depends(get_token)):
    return {"token": token}

client = TestClient(app)

def override_token():
    return None

app.dependency_overrides[get_token] = override_token

response = client.get("/secure")
print(response.status_code)
ABecause the endpoint requires authentication headers missing in the test
BBecause the dependency override was not applied correctly
CBecause the overridden dependency returns None, which FastAPI rejects for a required str parameter
DBecause the test client is not instantiated properly
Attempts:
2 left
💡 Hint

Think about how FastAPI validates dependency return values for required parameters.

❓ state_output
advanced
2:00remaining
What is the value of the global variable after running this FastAPI test with dependency override?

Given this code, what is the value of state['count'] after the test client calls the endpoint?

FastAPI
from fastapi import FastAPI, Depends
from fastapi.testclient import TestClient

app = FastAPI()
state = {"count": 0}

def increment():
    state["count"] += 1
    return state["count"]

@app.get("/count")
async def get_count(count=Depends(increment)):
    return {"count": count}

client = TestClient(app)

def override_increment():
    state["count"] += 10
    return state["count"]

app.dependency_overrides[increment] = override_increment

client.get("/count")
A10
B0
C1
D11
Attempts:
2 left
💡 Hint

Consider how the override changes the state and what the original function did before.

🧠 Conceptual
expert
2:00remaining
Which statement about FastAPI dependency overrides in tests is TRUE?

Choose the correct statement about how FastAPI handles dependency overrides during testing.

ADependency overrides can only override async dependencies, not sync ones
BDependency overrides only apply to the first request made by the test client
CDependency overrides automatically reset after each test function when using TestClient
DDependency overrides affect all requests globally until manually cleared or the app is restarted
Attempts:
2 left
💡 Hint

Think about the scope and lifetime of app.dependency_overrides.

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

  1. Step 1: Understand dependency overriding concept

    Overriding dependencies allows replacing real parts like database or external services with test doubles.
  2. Step 2: Identify the testing benefit

    This replacement isolates tests and makes them faster and more reliable.
  3. Final Answer:

    To replace real dependencies with test versions for isolated testing -> Option A
  4. 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

  1. Step 1: Recall FastAPI override syntax

    FastAPI uses the dictionary app.dependency_overrides to map original dependencies to test versions.
  2. Step 2: Match correct syntax

    Assigning test_dep to app.dependency_overrides[original_dep] is the correct way.
  3. Final Answer:

    app.dependency_overrides[original_dep] = test_dep -> Option C
  4. 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?
from fastapi import FastAPI, Depends
from fastapi.testclient import TestClient

app = FastAPI()

def get_number():
    return 10

@app.get("/number")
def read_number(num: int = Depends(get_number)):
    return {"number": num}

def override_get_number():
    return 42

app.dependency_overrides[get_number] = override_get_number

client = TestClient(app)
response = client.get("/number")
print(response.json())
medium
A. {"number": 42}
B. {"number": 10}
C. {"number": null}
D. RuntimeError due to dependency override

Solution

  1. Step 1: Understand dependency override effect

    The original get_number returns 10, but it is overridden by override_get_number returning 42.
  2. Step 2: Analyze the endpoint response

    The endpoint uses Depends(get_number), so it will receive 42 from the override.
  3. Final Answer:

    {"number": 42} -> Option A
  4. 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

  1. Step 1: Understand dependency_overrides lifecycle

    Overrides should be reset before each test to avoid conflicts from previous tests.
  2. Step 2: Identify cause of the test error

    If dependency_overrides is not cleared before tests, leftover overrides cause unexpected errors.
  3. Final Answer:

    Not resetting dependency_overrides before tests causes conflict -> Option B
  4. 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

  1. Step 1: Use dependency_overrides for test isolation

    Override the database session dependency only during tests to avoid affecting production code.
  2. 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.
  3. Final Answer:

    Set app.dependency_overrides[db_session] = get_test_db_session before tests and clear after -> Option D
  4. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard