0Pricing
FastAPI Backend Development Bootcamp · レッスン

FastAPIテストでの依存関係のモック

依存関係をオーバーライドし、外部サービスをモックすることで、テスト中にFastAPIのエンドポイントを分離する方法を学びます。

「FastAPIテストでの依存関係のモック」はCoddyKit上の無料FastAPI Backend Development Bootcampレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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テストでの依存関係のモック」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、FastAPI Backend Development Bootcampコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 FastAPI Backend Development Bootcampコースには全4レッスンが含まれています。

「FastAPIテストでの依存関係のモック」で何を学びますか?

依存関係をオーバーライドし、外部サービスをモックすることで、テスト中にFastAPIのエンドポイントを分離する方法を学びます。 ブラウザで直接実行するハンズオンコードでFastAPI Backend Development Bootcampを演習し、24時間対応の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に戻る