HTML 原文 · 完整 Markdown · 纯文本 · 分段目录 · ← 上一段 · 下一段 →

08-FastAPI 项目为什么要尽早上异步测试和 Ruff

第 21 / 26 段:依赖覆盖:在测试里替换外部依赖

FastAPI 工程化实践 · 发布 2026-03-28 · 更新 2026-11-11 · 标签:FastAPI、Testing、Ruff、DX

依赖覆盖:在测试里替换外部依赖(续)

@pytest_asyncio.fixture
async def client_with_mock_email(db_session: AsyncSession):
    sent_emails = []

    async def mock_email_service():
        class MockEmailService:
            async def send(self, to: str, subject: str, body: str):
                sent_emails.append({"to": to, "subject": subject})
        return MockEmailService()

    async def override_get_db():
        yield db_session

    app.dependency_overrides[get_db] = override_get_db
    app.dependency_overrides[get_email_service] = mock_email_service

    async with AsyncClient(
        transport=ASGITransport(app=app),
        base_url="http://test",
    ) as ac:
        yield ac, sent_emails

    app.dependency_overrides.clear()

@pytest.mark.asyncio
async def test_register_sends_welcome_email(client_with_mock_email):
    client, sent_emails = client_with_mock_email

    await client.post("/users/register", json={
        "email": "new@example.com",
        "password": "pass123",