การจำลองการพึ่งพาในการทดสอบ FastAPI
เรียนรู้วิธีแยกปลายทาง FastAPI ออกจากส่วนอื่นในการทดสอบ ด้วยการแทนที่การพึ่งพาและจำลองบริการภายนอก
การจำลองการพึ่งพาในการทดสอบ FastAPI เป็นบทเรียน FastAPI Backend Development Bootcamp ฟรีบน CoddyKit นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน 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_dbA 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_dbClearing 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_userVerifying 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 == 1Fixture-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 Backend Development Bootcamp ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 21
- บทเรียน
- 84
คำถามที่พบบ่อย
บทเรียน “การจำลองการพึ่งพาในการทดสอบ FastAPI” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การจำลองการพึ่งพาในการทดสอบ FastAPI” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส FastAPI Backend Development Bootcamp ให้อัปเกรดเป็น CoddyKit PRO คอร์ส FastAPI Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การจำลองการพึ่งพาในการทดสอบ FastAPI”
เรียนรู้วิธีแยกปลายทาง FastAPI ออกจากส่วนอื่นในการทดสอบ ด้วยการแทนที่การพึ่งพาและจำลองบริการภายนอก คุณปฏิบัติ FastAPI Backend Development Bootcamp ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน FastAPI Backend Development Bootcamp หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน FastAPI Backend Development Bootcamp บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน
บทเรียน “การจำลองการพึ่งพาในการทดสอบ FastAPI” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน FastAPI Backend Development Bootcamp นี้ได้ไหม
ได้ บทเรียน FastAPI Backend Development Bootcamp ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การทดสอบหน่วยด้วย Pytest
- การทดสอบการผสานรวมจุดปลายทาง FastAPI
- การแก้ไขข้อบกพร่องของแอปพลิเคชัน FastAPI
- การจำลองการพึ่งพาในการทดสอบ FastAPI