依赖覆盖:在测试里替换外部依赖(续)
@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",