0Pricing
FastAPI Backend Development Bootcamp · 课时

在 FastAPI 测试中模拟依赖

学习如何通过覆盖依赖和模拟外部服务,在测试中隔离 FastAPI 端点。

在 FastAPI 测试中模拟依赖 是 CoddyKit 上的免费 FastAPI Backend Development Bootcamp 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 FastAPI Backend Development Bootcamp 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 FastAPI Backend Development Bootcamp 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Why Mock Dependencies?

When testing a FastAPI endpoint, you often want to isolate the route logic from external systems like databases, payment gateways, or third-party APIs.

Mocking replaces those slow or unreliable parts with predictable fakes so your tests stay fast and deterministic.

FastAPI Dependency Overrides

FastAPI exposes app.dependency_overrides, a dictionary that maps a real dependency to a fake one during testing.

This is the cleanest way to swap a database session or auth check without touching production code.

app.dependency_overrides[get_db] = override_get_db

A Dependency to Override

Imagine an endpoint that depends on a database session.

from fastapi import Depends

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

@app.get("/users/{uid}")
def read_user(uid: int, db=Depends(get_db)):
    return db.query(User).get(uid)

Providing a Fake Session

In your test, define a function that yields an in-memory or test session, then register it as an override.

def override_get_db():
    db = TestingSessionLocal()
    try:
        yield db
    finally:
        db.close()

app.dependency_overrides[get_db] = override_get_db

Clearing Overrides

Always clear overrides after a test so they do not leak into other tests.

Use app.dependency_overrides.clear() in teardown or a pytest fixture finalizer.

app.dependency_overrides.clear()

Mocking with unittest.mock

For non-dependency code such as a helper that calls an external API, use unittest.mock.patch to replace the function.

from unittest.mock import patch

with patch("app.services.send_email") as mock_send:
    mock_send.return_value = True
    response = client.post("/signup", json=payload)
    mock_send.assert_called_once()

Using MagicMock Return Values

A MagicMock lets you script return values and inspect how it was called.

from unittest.mock import MagicMock

fake_client = MagicMock()
fake_client.charge.return_value = {"status": "ok"}

Mocking Async Functions

FastAPI is async-friendly. To mock an async dependency, use AsyncMock so awaiting it works correctly.

from unittest.mock import AsyncMock

mock_repo = AsyncMock()
mock_repo.get_user.return_value = {"id": 1, "name": "Ada"}

Mocking Auth Dependencies

To bypass authentication in a test, override the auth dependency to return a fake user.

def fake_current_user():
    return User(id=1, role="admin")

app.dependency_overrides[get_current_user] = fake_current_user

Verifying Mock Calls

Mocks record every interaction. Assert that your code called the dependency the expected way.

mock_send.assert_called_once_with(to="a@b.com")
assert mock_repo.save.call_count == 1

Fixture-Based Overrides

Wrap overrides in a pytest fixture for reuse and automatic cleanup.

import pytest

@pytest.fixture
def client_with_db():
    app.dependency_overrides[get_db] = override_get_db
    yield TestClient(app)
    app.dependency_overrides.clear()

Quick Check

Test your mocking knowledge.

Recap

You learned how to isolate FastAPI endpoints in tests:

  • dependency_overrides swaps dependencies like DB sessions or auth
  • patch / MagicMock / AsyncMock fake external functions
  • Always clear overrides after each test

Mocking keeps tests fast, deterministic, and focused on your own logic.

常见问题解答

「在 FastAPI 测试中模拟依赖」课时是免费的吗?

是的 — 「在 FastAPI 测试中模拟依赖」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 FastAPI Backend Development Bootcamp 课程的其余内容,请升级到 CoddyKit PRO。 FastAPI Backend Development Bootcamp 课程共包含 4 节课。

「在 FastAPI 测试中模拟依赖」这节课中我会学到什么?

学习如何通过覆盖依赖和模拟外部服务,在测试中隔离 FastAPI 端点。 你通过在浏览器中直接运行的动手代码来练习 FastAPI Backend Development Bootcamp,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 FastAPI Backend Development Bootcamp 需要有经验吗?

无需任何先前经验。CoddyKit 上的 FastAPI Backend Development Bootcamp 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「在 FastAPI 测试中模拟依赖」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 FastAPI Backend Development Bootcamp 课中编写并运行代码吗?

能。每节 FastAPI Backend Development Bootcamp 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 使用 Pytest 进行单元测试
  2. 测试 FastAPI 端点的集成
  3. 调试 FastAPI 应用
  4. 在 FastAPI 测试中模拟依赖
← 返回 FastAPI Backend Development Bootcamp