Java 后端面试题库 / 全部题解免费阅读理解原理,有条理地回答

FastAPI 的 dependency_overrides 如何替换依赖?

先说出你的答案

定义边界、关键机制、一个反例;P8题再补容量、失败与验证。

查看完整题解

参考回答

直接回答

app.dependency_overrides[原依赖] = 替代函数 可让测试忽略原依赖调用,使用可控结果。键应是注册时使用的依赖对象。

讲清原理

它修改的是应用实例上的测试配置。使用独立 app,或在测试结束用 finally 移除替换。真实逻辑也应有对应的集成测试。

例子与易错点

示例先确认生产读取值,再用替身读取测试值,移除覆盖后得到原结果,验证配置不会遗留给下一次测试。

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

app = FastAPI()

def repo_label():
    return "default-repository"

@app.get("/repository")
def read_label(label: Annotated[str, Depends(repo_label)]):
    return {"label": label}

with TestClient(app) as client:
    assert client.get("/repository").json()["label"] == "default-repository"
    app.dependency_overrides[repo_label] = lambda: "test-repository"
    try:
        assert client.get("/repository").json()["label"] == "test-repository"
    finally:
        app.dependency_overrides.pop(repo_label)
    assert client.get("/repository").json()["label"] == "default-repository"
print("override verified and removed")

相关题:第 69 题、第 70 题、第 71 题、第 73 题。

这道题,你掌握得怎么样?

掌握程度由你主动标记,阅读和收藏不会自动改变状态。