In a FastAPI test, how do you make an endpoint that depends on get_current_user run as a fixed test user?
answer
- a dict on the app object
- keyed by the original function
- value returns the fake user
- remove it when the test ends
basics
~10 sAdd an entry to app.dependency_overrides keyed by the original get_current_user function, whose value is a callable returning the test user; FastAPI calls it instead on every request, and the test removes the entry afterwards.
solid answer
~40 s`app.dependency_overrides` is a plain `dict` on the `FastAPI` instance. I set `app.dependency_overrides[get_current_user] = fake_current_user`, where `fake_current_user` returns a fixed `User`, and call the endpoint through `TestClient`. FastAPI consults that dict every time it resolves a dependency, so every path operation, router or decorator dependency that uses `get_current_user` gets the fake user. Because the original is never called, neither are its own sub-dependencies: the `OAuth2PasswordBearer` scheme never reads the `Authorization` header, so the request succeeds without a token. Finally I remove the entry when the test ends, in a `finally` block or a fixture's teardown, or the next test inherits the fake user.
code
python · 36 linesfrom typing import Annotated
from fastapi import Depends, FastAPI
from fastapi.security import OAuth2PasswordBearer
from fastapi.testclient import TestClient
from pydantic import BaseModel
app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
class User(BaseModel):
username: str
def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]) -> User:
raise NotImplementedError("decode and verify the token here")
@app.get("/orders/mine")
def my_orders(user: Annotated[User, Depends(get_current_user)]):
return {"owner": user.username}
def fake_current_user() -> User:
return User(username="alice")
def test_my_orders_as_alice():
app.dependency_overrides[get_current_user] = fake_current_user
try:
response = TestClient(app).get("/orders/mine") # no Authorization header
assert response.status_code == 200
assert response.json() == {"owner": "alice"}
finally:
app.dependency_overrides.clear()go deeper
Recall the exact line: app.dependency_overrides with the original function as key and a fake-user function as value. Mention removing it after the test.
Explain that FastAPI consults the dict on every request and that the original's sub-dependencies, such as the bearer scheme, no longer run.
Point out what the override stops proving: authentication is bypassed, so the token path needs its own test without overrides, and cleanup belongs in teardown.
Frame overrides as a team convention: fixtures own every override, fixed-user fakes are shared helpers, and a suite rule keeps at least one real-token test per protected router.
## What `app.dependency_overrides` is Every `FastAPI` application object carries an attribute called `dependency_overrides`. It is an ordinary Python `dict`, empty by default, and FastAPI's source documents it as existing "for testing, to replace expensive dependencies with testing versions". - The **key** is the original dependency callable: the exact object you passed to `Depends(...)`, here the function `get_current_user`. - The **value** is the replacement callable FastAPI should call instead. When FastAPI resolves the dependencies of a request, it looks each one up in this dict. If it finds the original as a key, it builds the dependency from the replacement and calls that; otherwise it calls the original. The lookup happens on every request, not when the app starts. ## Writing the override, step by step 1. Write a function that returns the user the test wants, for example `def fake_current_user() -> User: return User(username="alice")`. It usually takes no parameters. 2. Register it: `app.dependency_overrides[get_current_user] = fake_current_user`. Pass the function object itself, not a string and not a call (`fake_current_user`, not `fake_current_user()`). 3. Send the request with `TestClient(app)` and assert on the response. 4. Remove the entry when the test ends, with `app.dependency_overrides.clear()` or `app.dependency_overrides.pop(get_current_user, None)`, in a `finally` block or a pytest fixture's teardown so it runs even when an assertion fails. ## What the override skips The override replaces the original **and everything beneath it**. FastAPI resolves dependencies as a graph: `get_current_user` usually depends on `oauth2_scheme`, an `OAuth2PasswordBearer` instance that reads the `Authorization` header, and perhaps on a database session to load the user. With the override in place: - `get_current_user` is not called at all. - Its sub-dependencies are not resolved either, so the bearer scheme never runs and a request **without any token** reaches the endpoint. - Other dependencies the endpoint declares directly still run normally; only the overridden branch is replaced. - The generated OpenAPI schema does not change: `/docs` still shows the endpoint as protected, because the schema is built from the original declarations. This is exactly why the technique is useful: tests of business logic no longer need to mint and sign a real token, call an identity provider, or seed a user row just to get past authentication. It also means that a test using the override proves nothing about authentication itself; the token path needs its own test that sets no override. ## Where the override applies The FastAPI documentation notes that an override works wherever the original dependency is used: - as a parameter of a path operation function, typically through an `Annotated[User, Depends(get_current_user)]` alias; - in a path operation decorator's `dependencies=[...]` list; - in an `APIRouter(dependencies=[...])` or an `include_router(..., dependencies=[...])` call; - as a sub-dependency of another dependency. One override therefore covers every endpoint of the app at once. It does not cover a separate `FastAPI` sub-application attached with `app.mount`, which has its own `dependency_overrides` dict. ## Beginner mistakes | Mistake | What happens | |---|---| | Key is the string `"get_current_user"` | Never matched; the real dependency runs | | Key and value swapped | Never matched; the real dependency runs | | Monkeypatching the module attribute | The route already holds the original function object, so nothing changes | | No cleanup | The next test silently runs as the fake user | | Expecting a missing token to fail | The scheme was skipped, so the request succeeds | A related surprise: the override is inspected like any other dependency. If it declares a parameter, for example `role: str`, FastAPI treats it as a required query parameter and answers 422 when the test omits it, even though `/docs` never shows that parameter. Keep fixed-user overrides parameterless, or give the fake a closure over the values the test needs, for example a small factory that returns `lambda: User(username=name)` so each test can pick its user. ## Summary `app.dependency_overrides[get_current_user] = fake_current_user` is the whole mechanism: a dict keyed by the original callable, consulted on each request, applied everywhere the dependency appears, and replacing its whole sub-graph. The discipline around it, removing the entry after each test, matters as much as the line that adds it.
- Does the override function have to match get_current_user's signature?No. FastAPI inspects the override like any dependency, so its own parameters become request inputs or sub-dependencies. A zero-argument function is usual for a fixed user. If it declares `role: str`, that becomes a required query parameter, and a request without it gets a 422 even though `/docs` never lists it.
- Can the override be added after the TestClient was created?Yes. FastAPI reads `app.dependency_overrides` each time it resolves a request's dependencies, so an entry added or removed between two calls on the same `TestClient` takes effect on the next request. Nothing has to be rebuilt.
- The override key is the string name of the dependency function.
- Monkeypatching get_current_user in its module also changes what FastAPI calls.
- Overrides must be registered before TestClient(app) is created.
- The fake user still needs a valid bearer token in the request.
- FastAPI drops overrides automatically when the test function returns.